Complete the code to handle exceptions in a Spring Boot controller method.
public class MyController { @[1] public ResponseEntity<String> handleException(Exception ex) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred"); } }
The @ExceptionHandler annotation is used to define a method that handles exceptions thrown by controller methods.
Complete the code to specify which exception type the handler method should catch.
@ExceptionHandler([1].class) public ResponseEntity<String> handleNotFound(Exception ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found"); }
You specify the exception class inside @ExceptionHandler to catch that specific exception type.
Fix the error in the exception handler method signature to correctly handle exceptions.
@ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<String> handleException([1] ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage()); }
The method parameter should be the same exception type declared in @ExceptionHandler to access its specific methods.
Fill both blanks to create a global exception handler class with proper annotations.
@[1] public class GlobalExceptionHandler { @[2] public ResponseEntity<String> handleAllExceptions(Exception ex) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Server error"); } }
@ControllerAdvice marks the class as a global exception handler, and @ExceptionHandler marks the method to handle exceptions.
Fill all three blanks to handle a specific exception and return a custom message with status.
@ExceptionHandler([1].class) public ResponseEntity<String> handleCustomException([2] ex) { return ResponseEntity.status([3]).body("Custom error: " + ex.getMessage()); }
The method handles CustomException and returns a 400 Bad Request status with a custom message.