Bird
0
0

You want to create a custom exception handler that returns a JSON response with error details and HTTP 404 status when a resource is not found. Which approach correctly achieves this in Spring Boot?

hard📝 Conceptual Q8 of 15
Spring Boot - Exception Handling
You want to create a custom exception handler that returns a JSON response with error details and HTTP 404 status when a resource is not found. Which approach correctly achieves this in Spring Boot?
AHandle exception inside controller method and return null
BThrow NotFoundException and let Spring Boot return default HTML error page
CUse @ControllerAdvice with @ExceptionHandler for NotFoundException returning ResponseEntity with JSON body and status 404
DUse @RestControllerAdvice but return String with error message only
Step-by-Step Solution
Solution:
  1. Step 1: Choose global exception handler annotation

    @ControllerAdvice or @RestControllerAdvice can handle exceptions globally.
  2. Step 2: Return ResponseEntity with JSON and 404 status

    Returning ResponseEntity with JSON body and HttpStatus.NOT_FOUND provides correct response.
  3. Final Answer:

    Use @ControllerAdvice with @ExceptionHandler returning ResponseEntity with JSON and 404 -> Option C
  4. Quick Check:

    Global handler with ResponseEntity JSON and 404 status [OK]
Quick Trick: Return ResponseEntity with JSON and 404 in @ControllerAdvice [OK]
Common Mistakes:
  • Relying on default HTML error page
  • Returning plain String instead of JSON
  • Returning null from controller

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes