0PricingLogin
Spring Boot 4 Microservices & REST APIs · Lesson

@ControllerAdvice and @ExceptionHandler

Handle exceptions globally.

The Problem with Scattered Try/Catch

Handling errors with try/catch in every controller duplicates code and produces inconsistent responses. Spring MVC offers a centralized model: exception handlers that turn exceptions into clean HTTP responses.

Local @ExceptionHandler

A method annotated @ExceptionHandler inside a controller handles the listed exception types for that controller. It maps an exception to a response.

@RestController
public class OrderController {
    @ExceptionHandler(OrderNotFoundException.class)
    public ResponseEntity<String> handleNotFound(OrderNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
    }
}

All lessons in this course

  1. Bean Validation with @Valid
  2. Custom Validators
  3. @ControllerAdvice and @ExceptionHandler
  4. Problem Details (RFC 7807)
← Back to Spring Boot 4 Microservices & REST APIs