@ExceptionHandler Annotation Guide
The @ExceptionHandler annotation marks a method inside a @RestControllerAdvice or @Controller class as the official handler for a specific Exception class.
Handling MethodArgumentNotValidException (DTO Validation Errors)
When input DTO validation fails (e.g. `@NotBlank` or `@Email`), Spring throws a MethodArgumentNotValidException. Here is how to format field-level validation error messages for frontend forms:
Handling Validation Errors
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, Object>> handleValidationExceptions(MethodArgumentNotValidException ex) {
Map<String, String> fieldErrors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error -> {
fieldErrors.put(error.getField(), error.getDefaultMessage());
});
Map<String, Object> response = new HashMap<>();
response.put("timestamp", LocalDateTime.now());
response.put("status", 400);
response.put("error", "Validation Failed");
response.put("errors", fieldErrors);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
}
Sample JSON Output Returned to Frontend:
{
"timestamp": "2026-08-09T00:15:00",
"status": 400,
"error": "Validation Failed",
"errors": {
"email": "Please provide a valid email address",
"fullName": "Name cannot be empty"
}
}