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:
Step 1: Understand global exception handling
@ControllerAdvice allows defining exception handlers that apply to all controllers globally.
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.
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
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
Master "Exception Handling" in Spring Boot
9 interactive learning modes - each teaches the same concept differently