Complete the code to create a global exception handler class using @ControllerAdvice.
import org.springframework.web.bind.annotation.[1]; @[1] public class GlobalExceptionHandler { }
The @ControllerAdvice annotation marks a class as a global exception handler in Spring Boot.
Complete the method annotation to handle exceptions of type NullPointerException globally.
import org.springframework.web.bind.annotation.ExceptionHandler; @ExceptionHandler([1].class) public String handleNullPointer() { return "error-null"; }
The @ExceptionHandler annotation specifies which exception type the method handles. Here, it handles NullPointerException.
Fix the error in the method signature to correctly handle exceptions globally.
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.http.HttpStatus; @ExceptionHandler(Exception.class) @ResponseStatus([1]) public String handleAllExceptions(Exception ex) { return "error"; }
Using @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) tells Spring to return HTTP 500 for unhandled exceptions.
Fill both blanks to create a method that handles IllegalArgumentException and returns a custom error message.
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @ExceptionHandler([1].class) @ResponseBody public String handleIllegalArgument([2] ex) { return "Invalid argument: " + ex.getMessage(); }
The method handles IllegalArgumentException and takes it as a parameter to access the message.
Fill all three blanks to create a global handler that returns a ResponseEntity with status and body.
import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.http.HttpStatus; @ExceptionHandler([1].class) public ResponseEntity<String> handleCustomException([2] ex) { return ResponseEntity.status([3]).body("Custom error: " + ex.getMessage()); }
This method handles CustomException and returns a ResponseEntity with HTTP 400 Bad Request status and a custom message.