Bird
0
0

How should you implement this using @ControllerAdvice?

hard📝 Application Q15 of 15
Spring Boot - Exception Handling
You want to create a global error handler that returns JSON with error details for all exceptions except ResourceNotFoundException, which should return 404 status with a custom message. How should you implement this using @ControllerAdvice?
AUse a single @ExceptionHandler(Exception.class) method and check exception type inside to return different responses
BUse @ControllerAdvice only for ResourceNotFoundException and ignore other exceptions
CHandle ResourceNotFoundException in each controller separately, and use @ControllerAdvice only for other exceptions
DCreate two @ExceptionHandler methods: one for ResourceNotFoundException returning 404 JSON, another for Exception returning generic JSON with 500 status
Step-by-Step Solution
Solution:
  1. Step 1: Understand requirement for specific and general handling

    You need one handler for ResourceNotFoundException with 404 and custom JSON, and another for all other exceptions with generic 500 JSON.
  2. Step 2: Implement two separate @ExceptionHandler methods in @ControllerAdvice

    One method annotated with @ExceptionHandler(ResourceNotFoundException.class) returns 404 JSON; another with @ExceptionHandler(Exception.class) returns 500 JSON.
  3. Final Answer:

    Create two @ExceptionHandler methods: one for ResourceNotFoundException returning 404 JSON, another for Exception returning generic JSON with 500 status -> Option D
  4. Quick Check:

    Separate handlers for specific and general exceptions [OK]
Quick Trick: Use multiple @ExceptionHandler methods for different exceptions [OK]
Common Mistakes:
  • Using one method with manual type checks inside
  • Handling specific exceptions in controllers, not globally
  • Ignoring general exceptions in @ControllerAdvice

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes