Global Exception Handling with @RestControllerAdvice
Spring Boot APIs should return one consistent error format. @RestControllerAdvice with @ExceptionHandler methods maps exceptions to HTTP responses in one place, and ProblemDetail gives you the standard RFC 9457 shape.
What you will learn
- Handle exceptions globally with @RestControllerAdvice
- Return ProblemDetail responses
- Map validation errors to field-level messages
- Avoid leaking internal details
Key concepts
@RestControllerAdvice
A bean whose @ExceptionHandler methods apply to all controllers. The most specific matching exception type wins.
ProblemDetail
Spring 6+ class for RFC 9457 errors (type, title, status, detail, instance, plus custom properties). Turn on spring.mvc.problemdetails.enabled for built-in exceptions too.
ResponseStatusException
Throw it with a status and reason for quick cases without a custom exception class.
Step by step
One handler for the whole API
@RestControllerAdvice
class ApiExceptionHandler {
@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail notFound(OrderNotFoundException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
ProblemDetail invalid(MethodArgumentNotValidException ex) {
ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
pd.setTitle("Validation failed");
pd.setProperty("errors", ex.getFieldErrors().stream()
.map(f -> Map.of("field", f.getField(), "message", f.getDefaultMessage()))
.toList());
return pd;
}
@ExceptionHandler(Exception.class)
ProblemDetail unexpected(Exception ex) {
log.error("Unhandled error", ex);
return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong");
}
}Examples
The JSON a client receives
{
"type": "about:blank",
"title": "Validation failed",
"status": 400,
"instance": "/api/orders",
"errors": [ { "field": "quantity", "message": "must be greater than 0" } ]
}Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Map DataIntegrityViolationException (duplicate email) to 409 Conflict.
- Add a traceId property to every ProblemDetail.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
@ControllerAdvice vs @RestControllerAdvice?
@RestControllerAdvice is @ControllerAdvice plus @ResponseBody, so handler return values are serialised to JSON. Use it for REST APIs; @ControllerAdvice suits MVC apps that return views.
Can an exception handler be limited to some controllers?
Yes: @RestControllerAdvice(basePackages = "com.app.admin") or assignableTypes = {...}, or put an @ExceptionHandler method inside one controller to apply only there.
Summary
Handle exceptions once in @RestControllerAdvice, return ProblemDetail with field-level validation errors, log unexpected errors server-side, and never send stack traces to clients.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus