Bird
0
0

You want to create a global exception handler in Spring Boot that returns a JSON error with 404 status and a message when any ResourceNotFoundException occurs. Which approach correctly achieves this?

hard📝 Application Q15 of 15
Spring Boot - Exception Handling
You want to create a global exception handler in Spring Boot that returns a JSON error with 404 status and a message when any ResourceNotFoundException occurs. Which approach correctly achieves this?
AUse <code>@RestController</code> on the exception class and return 404 status
BAnnotate <code>ResourceNotFoundException</code> with <code>@ResponseStatus(HttpStatus.NOT_FOUND)</code> only, no handler needed
CCreate a class annotated with <code>@ControllerAdvice</code> and a method with <code>@ExceptionHandler(ResourceNotFoundException.class)</code> returning <code>ResponseEntity</code> with status 404 and error body
DThrow <code>ResponseStatusException</code> with 404 inside every controller method manually
Step-by-Step Solution
Solution:
  1. Step 1: Understand global exception handling

    Using @ControllerAdvice with @ExceptionHandler allows centralized handling of exceptions across controllers.
  2. Step 2: Return ResponseEntity with 404 and JSON body

    The handler method can build a ResponseEntity with HttpStatus.NOT_FOUND and a JSON error message for clients.
  3. Final Answer:

    Create a class annotated with @ControllerAdvice and a method with @ExceptionHandler(ResourceNotFoundException.class) returning ResponseEntity with status 404 and error body -> Option C
  4. Quick Check:

    Global handler + ResponseEntity = custom 404 JSON [OK]
Quick Trick: Use @ControllerAdvice + @ExceptionHandler for global JSON 404 [OK]
Common Mistakes:
  • Relying only on @ResponseStatus without custom JSON body
  • Annotating exception class as controller
  • Manually throwing exceptions in every method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes