Video in progress
Why does an advice with @ExceptionHandler(Exception.class) turn validation and 404 errors into 500s too, and how does ResponseEntityExceptionHandler help?
Spring MVC's internal errors (MethodArgumentNotValidException, HttpRequestMethodNotSupportedException, NoResourceFoundException) are also Exceptions; a general handler catches them and returns 500 instead of the right 4xx. If you extend ResponseEntityExceptionHandler, these errors come back with the standard status and a ProblemDetail.
📖 Answer
Many projects have an advice like this:
@RestControllerAdvice
class GlobalHandler {
@ExceptionHandler(Exception.class)
ResponseEntity<String> any(Exception e) {
return ResponseEntity.status(500).body("Ichki xato");
}
}
The result: malformed JSON → 500, GET instead of POST → 500, a nonexistent path (NoResourceFoundException in Spring 6.1+) → 500. Monitoring fills up with 5xx, and the client doesn't know what they did wrong.
The right structure:
@RestControllerAdvice
class GlobalHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail notFound(OrderNotFoundException e) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders h, HttpStatusCode s, WebRequest r) {
ProblemDetail pd = ex.getBody();
pd.setProperty("errors", ex.getFieldErrors().stream()
.map(f -> Map.of("field", f.getField(), "message", f.getDefaultMessage()))
.toList());
return ResponseEntity.status(s).body(pd);
}
@ExceptionHandler(Exception.class)
ProblemDetail unexpected(Exception e) {
log.error("Kutilmagan xato", e);
return ProblemDetail.forStatus(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Spring picks the most specific matching handler, so the Exception handler is now left only for errors that are truly unexpected.
One more subtle point: with several advices, they're checked in @Order and the first match runs, so an advice in a library can "steal" your handler.
Sign up to mark studied questions and save your progress.