Spring Boot 4 · Controllers and beans

Handle exceptions globally

Turn exceptions into HTTP responses for all controllers.

@RestControllerAdvice
public class ApiExceptionHandler {

    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String notFound(NotFoundException ex) {
        return ex.getMessage();
    }
}

Official Spring Boot 4 documentation

More controllers and beans commands

All controllers and beans commands · Spring Boot 4 cheatsheet

Was this page helpful?