Bird
0
0

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 catches RuntimeException for all controllers and returns a JSON error message with HTTP status 500. Which approach correctly achieves this?
ACreate a class annotated with <code>@ControllerAdvice</code> and define a method with <code>@ExceptionHandler(RuntimeException.class)</code> returning a JSON response and <code>@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)</code>.
BAdd <code>@ExceptionHandler(RuntimeException.class)</code> method inside each controller class returning a view name.
CUse <code>@RestController</code> on a class with <code>@ExceptionHandler(Exception.class)</code> returning a String message.
DConfigure exception handling in application.properties file.
Step-by-Step Solution
Solution:
  1. Step 1: Understand global exception handling

    @ControllerAdvice allows defining exception handlers that apply to all controllers globally.
  2. Step 2: Define handler method for RuntimeException

    Use @ExceptionHandler(RuntimeException.class) with @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) to set status 500 and return JSON response.
  3. Final Answer:

    Create a class annotated with @ControllerAdvice and define a method with @ExceptionHandler(RuntimeException.class) returning a JSON response and @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR). -> Option A
  4. Quick Check:

    Global handler uses @ControllerAdvice + @ExceptionHandler [OK]
Quick Trick: Use @ControllerAdvice for global exception handling [OK]
Common Mistakes:
  • Putting handlers only inside controllers for global effect
  • Using application.properties for exception handling
  • Not setting proper HTTP status in handler

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes