Difficulty: Intermediate
How do you handle exceptions globally in a Spring Boot REST API instead of writing try-catch in every controller?
Picture a hospital with no central emergency desk, where every ward improvises how to handle a crisis. That is what an API looks like when each controller catches its own exceptions: inconsistent status codes, different JSON shapes, and stack traces leaking to clients. Global exception handling is the emergency desk. You define one place that translates every exception into a predictable HTTP response.
The mechanism is @ControllerAdvice, or @RestControllerAdvice, which is @ControllerAdvice plus @ResponseBody. It marks a class whose methods apply across all controllers. Inside, each method annotated with @ExceptionHandler declares which exception types it handles, and returns a response. When a controller throws, Spring's HandlerExceptionResolver infrastructure, specifically ExceptionHandlerExceptionResolver, looks for the most specific matching handler and invokes it, so a handler for ResourceNotFoundException wins over one for RuntimeException.
A good design has several layers. Define a small hierarchy of domain exceptions, for example ResourceNotFoundException mapping to 404, DuplicateResourceException mapping to 409, and BusinessRuleException mapping to 422 or 400. Throw them from the service layer, where the business knowledge lives, and translate to HTTP only in the advice, so services never need to know about status codes. Add handlers for framework exceptions too: MethodArgumentNotValidException for validation, HttpMessageNotReadableException for bad JSON, and AccessDeniedException for authorisation. Finish with a catch-all handler for Exception that logs the full stack trace with a correlation id and returns a generic 500 message. Never send the stack trace or SQL details back, since that leaks internals.
Response shape matters. Choose a consistent structure with timestamp, status, error code, message, and path, and use the same for every error. Spring 6 and Boot 3 also support RFC 7807 Problem Details through the ProblemDetail class and the property spring.mvc.problemdetails.enabled=true, giving a standard application/problem+json format that clients and API gateways understand. You can extend ResponseEntityExceptionHandler to inherit sensible handling for the many built-in MVC exceptions and override only what you need.
Limits worth knowing: @ControllerAdvice handles exceptions thrown from controllers. Exceptions from servlet filters, such as a failing JWT filter in Spring Security, occur before the DispatcherServlet and bypass the advice, so they need an AuthenticationEntryPoint or a filter-level handler. Also remember the difference between @ResponseStatus on an exception class, which is a quick option for simple cases, and the advice approach, which offers full control.
You can scope an advice to certain controllers using basePackages, assignableTypes, or annotations, which helps in large codebases with separate public and admin APIs. In tests, @WebMvcTest loads the advice automatically, so you can assert error responses with MockMvc.
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String resource, Object id) {
super(resource + " not found with id " + id);
}
}
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ProblemDetail notFound(ResourceNotFoundException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
}
@ExceptionHandler(DataIntegrityViolationException.class)
public ProblemDetail conflict(DataIntegrityViolationException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, "Duplicate or invalid data");
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> fallback(Exception ex) {
String id = UUID.randomUUID().toString();
log.error("Unhandled error {}", id, ex); // full detail only in logs
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "Internal error", "reference", id));
}
}
Services throw domain exceptions; the advice alone decides the HTTP status and JSON shape.
ControllerAdvice, ExceptionHandler, ProblemDetail, Error Handling