Video in progress

Junior 🌱 Spring

How do you catch exceptions thrown in controllers in one place and return a clean response?

You write @ExceptionHandler methods in a @RestControllerAdvice class: the status and response body for each exception type live in one place.

📖 Answer

Instead of writing try/catch in every controller:

@RestControllerAdvice
public class ApiErrors {

    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ProblemDetail notFound(NotFoundException e) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ProblemDetail invalid(MethodArgumentNotValidException e) {
        ProblemDetail p = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
        p.setProperty("fields", e.getBindingResult().getFieldErrors().stream()
                .map(f -> f.getField() + ": " + f.getDefaultMessage()).toList());
        return p;
    }
}

ProblemDetail (Spring 6) is the standard error format from RFC 9457: type, title, status, detail.

Add a handler for unexpected Exception too, but don't send the client a stack trace or an SQL error. You write it to the log, and the client gets a generic "internal error" message plus the request id — later you find it in the log by that id.