import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.http.ResponseEntity; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(NullPointerException.class) public ResponseEntity<String> handleNullPointer(Exception ex) { return ResponseEntity.status(400).body("Null pointer error caught globally"); } } // In some controller: // public String someMethod() { // throw new NullPointerException(); // }
@ControllerAdvice with @ExceptionHandler methods catches exceptions thrown in any controller globally. Here, NullPointerException is caught and a custom response is returned.
The method must accept the exception type to handle and return a response (like ResponseEntity or String). Option A matches this pattern.
@ControllerAdvice alone does not serialize return values as JSON or response bodies. Using @RestControllerAdvice ensures the response is sent as JSON or text. Without it, the handler may not work as expected for REST APIs.
By default, @ControllerAdvice applies globally to all controllers in the Spring Boot application unless filters like basePackages or assignableTypes are specified.
The handler sets the HTTP status to 409 Conflict explicitly, so the client receives status 409.