Complete the code to define a custom exception class named ResourceNotFoundException.
public class ResourceNotFoundException extends [1] { public ResourceNotFoundException(String message) { super(message); } }
The custom exception should extend RuntimeException to be an unchecked exception suitable for Spring Boot.
Complete the code to annotate the exception handler method to catch ResourceNotFoundException.
@[1](ResourceNotFoundException.class) public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage()); }
@ExceptionHandler is used to mark a method that handles specific exceptions in Spring Boot.
Fix the error in the exception handler method to return NOT_FOUND status correctly.
return ResponseEntity.status([1]).body(ex.getMessage());
HttpStatus.NOT_FOUND (404) is the correct status code to indicate a resource was not found.
Fill both blanks to create a global exception handler class with proper annotation and method signature.
@[1] public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<String> [2](ResourceNotFoundException ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage()); } }
@ControllerAdvice marks the class as a global exception handler. The method name can be descriptive like handleResourceNotFound.
Fill all three blanks to throw the custom exception when a resource is not found in the service method.
public Resource getResourceById(Long id) {
return repository.findById(id).orElseThrow(() -> new [1]([2]));
}
// Message constant
private static final String [3] = "Resource not found with id: ";The method throws ResourceNotFoundException with a message. The message constant is named NOT_FOUND_MESSAGE.