Stop 14 · Spring Boot & Backend DevelopmentTopics · 6/13

Global Exception Handling

Part of the Java Roadmap

In short

Without a plan, errors reach clients as ugly stack traces or random 500s. One @RestControllerAdvice class turns every error into a clean, predictable JSON response.

A class annotated with @RestControllerAdvice and @ExceptionHandler methods turns exceptions into consistent JSON error responses with the right HTTP status, instead of leaking stack traces.

The jaadu wearing a headset sits at a help desk, calmly sorting a pile of small problem items like a broken chair leg and a cracked mug into colour-coded trays.

Think of it like this

The help desk

In a big Hyderabad office, any problem, whether a broken chair, a laptop crash or a lost ID card, goes to one help desk. They log it the same way and reply in a standard format with a ticket number. @RestControllerAdvice is that help desk for your API: every exception lands there and gets a standard reply.

Watch it happen

From exception to JSON

Controller
Service
Exception
@RestControllerAdvice
404 JSON

1/5GET /api/products/99 reaches the controller.

The big ideas

What you need to know

@RestControllerAdvice

A class whose handlers apply to all controllers. Return values become JSON.

@ExceptionHandler

Each method handles one or more exception types and returns the response for them.

ProblemDetail

Spring 6's built-in RFC 9457 error body with type, title, status and detail fields.

Hide internals

Have a catch-all handler for Exception that logs the stack trace but returns a generic 500 message.

See it in code

Walk through the code

java
1import org.springframework.http.*;2import org.springframework.web.bind.MethodArgumentNotValidException;3import org.springframework.web.bind.annotation.*;4import org.slf4j.Logger;5import org.slf4j.LoggerFactory;6import java.util.Map;7import java.util.stream.Collectors;8 9class ProductNotFoundException extends RuntimeException {10    ProductNotFoundException(Long id) { super("Product " + id + " not found"); }11}12 13@RestControllerAdvice14public class GlobalExceptionHandler {15    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);16 17    @ExceptionHandler(ProductNotFoundException.class)18    public ProblemDetail notFound(ProductNotFoundException ex) {19        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());20    }21 22    @ExceptionHandler(MethodArgumentNotValidException.class)23    public ProblemDetail invalid(MethodArgumentNotValidException ex) {24        Map<String, String> errors = ex.getBindingResult().getFieldErrors().stream()25            .collect(Collectors.toMap(e -> e.getField(), e -> String.valueOf(e.getDefaultMessage()), (a, b) -> a));26        ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Validation failed");27        pd.setProperty("errors", errors);28        return pd;29    }30 31    @ExceptionHandler(Exception.class)32    public ProblemDetail unexpected(Exception ex) {33        log.error("Unhandled error", ex);34        return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong");35    }36}

1/4A custom unchecked exception the service can throw.

The validation handler returns a map like {"email": "Enter a valid email"} inside the ProblemDetail.

Save yourself the pain

Common mistakes

Oops

Wrapping every controller method in try-catch.

Do this instead

Let exceptions bubble up and handle them once, centrally, in the advice class.

Oops

Returning ex.getMessage() for every unexpected exception.

Do this instead

Internal messages can leak SQL or class names. Log them, and send a generic message to the client.

Oops

Using @ControllerAdvice and getting HTML or view errors.

Do this instead

For APIs use @RestControllerAdvice, which adds @ResponseBody to every handler.

Your mission

Clean errors everywhere

~30 min

Quick check

What does @RestControllerAdvice add compared to @ControllerAdvice?

Go deeper

  1. 1Throw a custom ResourceNotFoundException and map it to 404.
  2. 2Return validation errors as a clear list of field messages.
  3. 3Use one error response format across the whole API.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge