Complete the code to extend the class for handling exceptions globally.
public class GlobalExceptionHandler extends [1] { }
The class should extend ResponseEntityExceptionHandler to customize exception handling in Spring Boot.
Complete the annotation to mark the class as a global exception handler.
@[1] public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { }
The @ControllerAdvice annotation marks the class to handle exceptions globally across controllers.
Fix the method signature to override the handler for MethodArgumentNotValidException.
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException [1],
HttpHeaders headers, HttpStatus status, WebRequest request) {
// method body
}The parameter name can be anything, but ex is commonly used and matches the override signature.
Fill both blanks to create a ResponseEntity with a custom error message and BAD_REQUEST status.
return new ResponseEntity<>([1], [2]);
The first blank is the body object (like errorDetails), and the second blank is the HTTP status HttpStatus.BAD_REQUEST.
Fill all three blanks to build a map of field errors inside the exception handler.
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error -> {
errors.put(error.getField(), [1]);
});
return new ResponseEntity<>([2], [3]);The map stores field names and their default messages. Then the map is returned with BAD_REQUEST status.