100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Java

Exception Handling in Spring Boot

Learn how to handle errors gracefully in Spring Boot REST APIs using @ExceptionHandler, @ControllerAdvice, and structured error responses.

Web LayerIntermediate10 min readJul 10, 2026
Analogies

Why Centralized Exception Handling Matters

Without explicit handling, an uncaught exception in a Spring Boot controller results in a generic 500 Internal Server Error with Spring Boot's default Whitelabel Error Page or a bare JSON error body, exposing little useful information to API consumers and potentially leaking stack traces in non-production configurations. Centralized exception handling lets you map specific exception types to specific HTTP status codes and consistent, structured error bodies across your entire API, rather than scattering try-catch blocks through every controller method.

🏏

Cricket analogy: It's like having a single, trained match referee handle all disputes consistently across every game, instead of each umpire on the field making up their own rules for what counts as an appeal — centralized handling keeps error responses consistent.

@ExceptionHandler and @ControllerAdvice

@ExceptionHandler, placed on a method, tells Spring to invoke that method whenever a specified exception type (or subtype) is thrown within the same controller. To apply this handling globally across all controllers rather than duplicating it per class, combine it with @ControllerAdvice (or @RestControllerAdvice, which adds implicit @ResponseBody) on a dedicated class. Spring matches the most specific exception type first, so a handler for IllegalArgumentException takes precedence over a broader handler for Exception when both could apply.

🏏

Cricket analogy: Like the ICC's central code of conduct that applies across every international match, rather than each cricket board writing its own disciplinary rules — @ControllerAdvice centralizes handling the same way.

java
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
        ErrorResponse body = new ErrorResponse("NOT_FOUND", ex.getMessage());
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(body);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex) {
        String message = ex.getBindingResult().getFieldErrors().stream()
                .map(err -> err.getField() + ": " + err.getDefaultMessage())
                .collect(Collectors.joining("; "));
        return ResponseEntity.badRequest().body(new ErrorResponse("VALIDATION_ERROR", message));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleGeneric(Exception ex) {
        return ResponseEntity.internalServerError()
                .body(new ErrorResponse("INTERNAL_ERROR", "Unexpected error occurred"));
    }
}

Custom Exceptions and Meaningful Status Codes

Rather than throwing generic RuntimeException everywhere, define custom exception classes such as ResourceNotFoundException or DuplicateEmailException that carry semantic meaning about what went wrong. Each custom exception maps cleanly to a specific HTTP status in its handler — 404 for not-found, 409 for conflicts, 400 for bad input — which makes API behavior predictable for consumers and keeps service-layer code expressive: throwing new ResourceNotFoundException("Order " + id) reads far better than a raw RuntimeException with a string message.

🏏

Cricket analogy: Like distinguishing a 'run out' from a 'stumping' from a 'caught behind' on the scorecard instead of just logging 'batsman is out' — each specific dismissal type carries distinct meaning, just as each custom exception maps to a distinct status.

Spring Boot 3's ProblemDetail (RFC 7807) class is a built-in alternative to hand-rolled error DTOs. Returning ResponseEntity<ProblemDetail> from an @ExceptionHandler gives you a standardized error format (type, title, status, detail, instance) out of the box.

Never let an @ExceptionHandler(Exception.class) leak raw exception messages or stack traces to the client in production — these can reveal internal class names, SQL fragments, or file paths. Log the full exception server-side and return a generic, safe message to the caller.

  • Uncaught exceptions default to a generic 500 error unless explicitly handled.
  • @ExceptionHandler maps a specific exception type to custom response logic within a controller.
  • @RestControllerAdvice applies exception handling globally across all controllers, with implicit @ResponseBody.
  • Spring resolves the most specific matching exception handler first.
  • Custom exception classes (ResourceNotFoundException, DuplicateEmailException) carry semantic meaning tied to specific HTTP statuses.
  • Spring Boot's built-in ProblemDetail class offers a standardized RFC 7807 error response format.
  • Never expose raw stack traces or internal error details to API clients in production.

Practice what you learned

Was this page helpful?

Topics covered

#Java#SpringBootStudyNotes#WebDevelopment#ExceptionHandlingInSpringBoot#Exception#Handling#Spring#Boot#ErrorHandling#StudyNotes#SkillVeris