Sub topic 2
How Spring MVC Turns an Exception into a Response
Assume you know basic Java exceptions, Spring Boot controllers, HTTP status codes, and Maven or Gradle.
The resolution flow
When a controller throws an exception, Spring MVC does not immediately send the exception to the client. Its exception-resolution chain checks registered resolvers in order. A matching @ExceptionHandler, controller advice, or status mapping can create a response. If nothing handles the exception, Spring Boot's default /error endpoint creates a generic error response.
Quick status mappings
@ResponseStatus attaches an HTTP status to an exception class. It is simple, but it couples the exception to HTTP.
ResponseStatusException sets the status at the throw site. It suits small cases where a dedicated exception class adds little value.
if (customer == null) {
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "Customer was not found");
}Local exception handlers
A method annotated with @ExceptionHandler handles matching exceptions inside one controller. This keeps behavior near the endpoint, but the same logic may be repeated across controllers.
@ExceptionHandler(IllegalArgumentException.class)
ProblemDetail handleBadArgument(IllegalArgumentException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, ex.getMessage());
problem.setTitle("Invalid request");
return problem;
}Global handlers with `@RestControllerAdvice`
Use @RestControllerAdvice for rules shared by the whole API. It combines controller advice with response-body serialization.
@RestControllerAdvice
class ApiExceptionHandler {
@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail handleMissing(OrderNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Order not found");
return problem;
}
}Consistent bodies with `ProblemDetail`
ProblemDetail represents an RFC 9457 problem response. It provides fields such as status, title, and detail, and supports custom properties. Use stable titles and safe details. Do not return stack traces, SQL, or internal class names.
Exercise
Which handler should contain an error rule shared by every controller?
Show answer
A method in a class annotated with @RestControllerAdvice.