Validation Error Handling

Validation error handling catches the exception that Spring throws when validation fails and turns it into a clear, structured response.It is used so the client gets “which field failed and why” instead of a long default Spring error or a server error. It is done with a @RestControllerAdvice class containing @ExceptionHandler methods, so one place handles errors for all controllers. Every error comes back in the same JSON shape, with a status, a message and an errors map of field: message.

Features

  • One global handler (GlobalExceptionHandler) for all controllers, so there is no try/catch in the controller.
  • Field-level messages, for example "age": "Age must be at least 18".
  • The same response format for every error.
  • Handles several kinds of failure, not only @Valid (see the table below).
  • Correct HTTP status codes: 400, 404, 409 and 500.
  • The generic 500 handler hides internal details from the client.

Validation Error Handling Types

Failure Exception caught Status Example
Body validation (@Valid @RequestBody) MethodArgumentNotValidException 400 Name too short, bad email
Parameter validation (@RequestParam, @PathVariable) ConstraintViolationException 400 /students/by-age?age=5
Unreadable or wrong-type JSON HttpMessageNotReadableException 400 "age": "twenty", broken JSON
Wrong type or missing value in the URL MethodArgumentTypeMismatchException, MissingServletRequestParameterException 400 /students/abc, no age param
Business-rule error (custom exception) DuplicateEmailException 409 Email already registered
Resource not found (custom exception) StudentNotFoundException 404 /students/99
Unexpected error Exception 500 Any bug, with a safe message
Scroll to Top