Skip to content
>_KernelBrief
Programming

Spring Boot Global Exception Handling with @RestControllerAdvice and ProblemDetail

Spring Boot global exception handling with @RestControllerAdvice and ProblemDetail (RFC 9457): consistent JSON errors, validation messages and a safe 500.

By Published 10 min read
// CODE
Table of contents

Spring Boot global exception handling means catching exceptions from every controller in one place — a class annotated with @RestControllerAdvice — and turning each one into a consistent JSON error response. On Spring Boot 3 and 4, the cleanest way to do it is to extend ResponseEntityExceptionHandler and return ProblemDetail, Spring's built-in implementation of the RFC 9457 "problem details" standard.

Most tutorials stop at a single @ExceptionHandler returning a home-made ErrorResponse class. That works, but it leaves Spring's own exceptions (bad JSON, wrong HTTP method, missing parameters, unknown URLs) returning a different format, and it often leaks stack traces on 500 errors. This guide builds a complete handler that covers all of that.

Versions: the code targets Spring Boot 4.x (Spring Framework 7, current release line 4.1) on Java 17 or newer, and uses only APIs that also exist in Spring Boot 3.x.

The quick answer: what you need

Piece What it does
@RestControllerAdvice class One global place for exception handlers; return values become the JSON body
extends ResponseEntityExceptionHandler Handles Spring MVC's built-in exceptions (400, 404, 405, 415…) as ProblemDetail
@ExceptionHandler(YourException.class) Maps your own exceptions to a status and message
Override handleMethodArgumentNotValid Adds field-level validation errors to the response
Catch-all @ExceptionHandler(Exception.class) Returns a safe, generic 500 and logs the real cause

The response for a missing resource then looks like this (Content-Type: application/problem+json):

{
  "type": "https://api.example.com/problems/not-found",
  "title": "Resource not found",
  "status": 404,
  "detail": "Book with id 42 was not found",
  "instance": "/api/books/42"
}

Why not just use try/catch or the default /error page?

Without any handling, Spring Boot forwards uncaught exceptions to its /error endpoint, which returns a generic body with a timestamp, status, error name and path. It works, but:

  • every exception you throw becomes a 500 Internal Server Error unless you annotate it or map it,
  • the message is hidden by default, so clients cannot tell why a request failed,
  • the format is Spring Boot's own, not a standard that client libraries recognise.

Wrapping each controller method in try/catch fixes the status codes but repeats the same code everywhere. A controller advice centralises it: Spring's documentation describes @ControllerAdvice as a way to apply @ExceptionHandler methods across all controllers.

Options compared

Approach Scope Handles Spring's built-in errors Best for
@ExceptionHandler inside a controller That controller only No A one-off case specific to one controller
@ResponseStatus on an exception class Wherever it's thrown No Quick status mapping, no custom body
throw new ResponseStatusException(...) Wherever it's thrown — Prototypes; mixes HTTP into service code
@RestControllerAdvice + ResponseEntityExceptionHandler Whole application Yes Production REST APIs

Use a local @ExceptionHandler when one controller needs special treatment — local handlers take precedence over global ones. Use @RestControllerAdvice for everything else.

Step 1: Create a custom exception

Keep domain exceptions free of HTTP details. Your service layer throws them; the advice decides the status code.

package com.example.books.error;

public class ResourceNotFoundException extends RuntimeException {

    public ResourceNotFoundException(String resource, Object id) {
        super(resource + " with id " + id + " was not found");
    }
}

A second exception for business-rule conflicts is often useful too:

package com.example.books.error;

public class DuplicateResourceException extends RuntimeException {

    public DuplicateResourceException(String message) {
        super(message);
    }
}

Step 2: Throw it from the service, not the controller

package com.example.books;

import com.example.books.error.ResourceNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class BookService {

    private final BookRepository repository;

    public BookService(BookRepository repository) {
        this.repository = repository;
    }

    public Book findById(Long id) {
        return repository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Book", id));
    }
}

The controller stays clean — no try/catch, no ResponseEntity juggling:

package com.example.books;

import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/books")
public class BookController {

    private final BookService service;

    public BookController(BookService service) {
        this.service = service;
    }

    @GetMapping("/{id}")
    public Book get(@PathVariable Long id) {
        return service.findById(id);
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Book create(@Valid @RequestBody CreateBookRequest request) {
        return service.create(request);
    }
}

For @Valid to work, add the validation starter (spring-boot-starter-validation) and put constraints on the request type:

package com.example.books;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;

public record CreateBookRequest(
        @NotBlank String title,
        @NotBlank String author,
        @Positive int pages) {
}

Step 3: Write the global exception handler

This is the core of Spring Boot global exception handling. One class handles your exceptions, Spring's built-in exceptions and anything unexpected.

package com.example.books.error;

import jakarta.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    private static final String TYPE_BASE = "https://api.example.com/problems/";

    // 404 — your own "not found" exception
    @ExceptionHandler(ResourceNotFoundException.class)
    public ProblemDetail handleNotFound(ResourceNotFoundException ex, HttpServletRequest request) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
        problem.setTitle("Resource not found");
        problem.setType(URI.create(TYPE_BASE + "not-found"));
        problem.setInstance(URI.create(request.getRequestURI()));
        return problem;
    }

    // 409 — business-rule conflict
    @ExceptionHandler(DuplicateResourceException.class)
    public ProblemDetail handleConflict(DuplicateResourceException ex, HttpServletRequest request) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, ex.getMessage());
        problem.setTitle("Resource already exists");
        problem.setType(URI.create(TYPE_BASE + "conflict"));
        problem.setInstance(URI.create(request.getRequestURI()));
        return problem;
    }

    // 400 — @Valid failures on @RequestBody, with one message per field
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
            MethodArgumentNotValidException ex, HttpHeaders headers,
            HttpStatusCode status, WebRequest request) {

        Map<String, String> errors = new LinkedHashMap<>();
        for (FieldError fe : ex.getBindingResult().getFieldErrors()) {
            errors.putIfAbsent(fe.getField(), fe.getDefaultMessage());
        }

        ProblemDetail problem = ex.getBody(); // Spring's pre-built 400 ProblemDetail
        problem.setTitle("Validation failed");
        problem.setDetail("One or more fields are invalid");
        problem.setType(URI.create(TYPE_BASE + "validation"));
        problem.setProperty("errors", errors);

        return handleExceptionInternal(ex, problem, headers, status, request);
    }

    // 500 — anything you did not anticipate: log it, never leak it
    @ExceptionHandler(Exception.class)
    public ProblemDetail handleUnexpected(Exception ex, HttpServletRequest request) {
        log.error("Unhandled exception on {} {}", request.getMethod(), request.getRequestURI(), ex);
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
                HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred");
        problem.setTitle("Internal server error");
        problem.setType(URI.create(TYPE_BASE + "internal"));
        return problem;
    }
}

What each part does:

  • Returning ProblemDetail from an @ExceptionHandler is enough: Spring sets the HTTP status from its status field and renders it as application/problem+json, as described in the Error Responses reference.
  • Extending ResponseEntityExceptionHandler gives you handling for every Spring MVC exception that implements ErrorResponse — malformed JSON, unsupported media types, wrong HTTP methods, missing request parameters, type mismatches and more — all in the same format as your own errors.
  • ex.getBody() works because MethodArgumentNotValidException already carries a ProblemDetail; you just enrich it.
  • setProperty("errors", ...) adds a non-standard field. With Jackson, Spring renders entries from ProblemDetail's properties map as top-level JSON fields, which RFC 9457 explicitly allows as "extension members".
  • The catch-all handler only fires for exceptions no more specific handler matched. Spring picks the closest match in the exception hierarchy, so it does not swallow your 404s or Spring's built-in 4xx errors.

Do you still need spring.mvc.problemdetails.enabled?

No. That Spring Boot property simply registers a default ResponseEntityExceptionHandler for built-in exceptions. Once you declare your own subclass, Boot's auto-configured one backs off. The property is useful only if you want RFC 9457 responses for Spring's exceptions without writing an advice class.

Step 4: Check the responses

Run the application and try a few requests with curl.

A missing book:

curl -i http://localhost:8080/api/books/42

returns 404 with the problem body shown at the top of this article.

An invalid request body:

curl -i -X POST http://localhost:8080/api/books \
  -H "Content-Type: application/json" \
  -d '{"title":"","author":"Ada","pages":-1}'

returns 400 with field-level details:

{
  "type": "https://api.example.com/problems/validation",
  "title": "Validation failed",
  "status": 400,
  "detail": "One or more fields are invalid",
  "errors": {
    "title": "must not be blank",
    "pages": "must be greater than 0"
  }
}

The exact default messages come from Hibernate Validator and your locale. Whether instance is filled in for Spring's built-in exceptions depends on the version: the Spring Framework 7.1 reference notes that the framework no longer sets instance to the request path automatically, so set it yourself (as the custom handlers above do) if clients rely on it.

Making your own exceptions RFC 9457-aware (alternative)

Instead of writing one @ExceptionHandler per exception, you can let exceptions describe themselves by extending Spring's ErrorResponseException:

package com.example.books.error;

import java.net.URI;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.ErrorResponseException;

public class BookNotFoundException extends ErrorResponseException {

    public BookNotFoundException(Long id) {
        super(HttpStatus.NOT_FOUND, problem(id), null);
    }

    private static ProblemDetail problem(Long id) {
        ProblemDetail pd = ProblemDetail.forStatusAndDetail(
                HttpStatus.NOT_FOUND, "Book with id " + id + " was not found");
        pd.setTitle("Resource not found");
        pd.setType(URI.create("https://api.example.com/problems/not-found"));
        return pd;
    }
}

ResponseEntityExceptionHandler already handles any ErrorResponseException, so no extra handler method is needed.

Use plain exceptions + handlers when you want a service layer that knows nothing about HTTP (the cleaner design for larger codebases). Use ErrorResponseException when the exception is clearly web-facing and you want less boilerplate.

Customising messages and translating errors

Spring resolves the title and detail of built-in exceptions through MessageSource, using codes such as problemDetail.title.<fully.qualified.ExceptionName> and problemDetail.<fully.qualified.ExceptionName>. That lets you change or translate messages in messages.properties without code:

problemDetail.title.org.springframework.web.HttpRequestMethodNotSupportedException=Method not allowed
problemDetail.org.springframework.web.HttpRequestMethodNotSupportedException=Method {0} is not supported. Use: {1}

The reference documentation lists the arguments available for each exception (for example {0} is the method and {1} the supported methods above).

Common pitfalls

  1. The advice is never called. It must be in (or below) the package of your @SpringBootApplication class, or be imported explicitly.
  2. Errors from Spring Security don't go through the advice. Authentication and authorization failures usually happen in servlet filters, before any controller runs. Configure an AuthenticationEntryPoint and AccessDeniedHandler for those.
  3. Two catch-all handlers. Having both your own @ExceptionHandler(Exception.class) and a second advice that does the same leads to unpredictable precedence. Keep one, or order advices with @Order.
  4. Leaking internals. Never put ex.getMessage() of an unexpected exception (SQL errors, file paths, class names) into a 500 response. Log it with a correlation or trace ID instead. This matters for security as much as tidiness — internal details help attackers map your stack, as incidents like Java4Shell show how quickly Java-specific weaknesses get targeted.
  5. Overriding handleExceptionInternal carelessly. If you override it to change every response, keep calling super or you can lose the headers (such as Allow for 405 errors) that Spring adds.
  6. Using @ControllerAdvice without @ResponseBody. Spring then treats return values as view names. Use @RestControllerAdvice for APIs.

Spring Boot 3 vs Spring Boot 4: what changes

The exception-handling APIs used here — ProblemDetail, ErrorResponse, ErrorResponseException and ResponseEntityExceptionHandler — were introduced in Spring Framework 6.0 and carry over to Spring Framework 7, which Spring Boot 4.0 is built on. The main things to watch when upgrading are around them rather than in them: Spring Boot 4 splits the codebase into smaller modules with renamed starters, moves to a newer Jackson major version, and keeps Java 17 as the minimum. Check the official Spring Boot 4.0 migration guide before upgrading a real project; the handler class itself should not need changes.

Next steps

Once errors are consistent, package the service so it runs the same everywhere — our Docker for beginners guide walks through images and a first Dockerfile. If you keep your handler and API changes on feature branches, Git merge vs rebase explains how to integrate them cleanly. And if you use AI assistants to generate boilerplate like the handlers above, the prompt engineering guide for developers covers how to get code that matches your project's conventions.

Frequently asked questions

+What is the difference between @ControllerAdvice and @RestControllerAdvice?

@RestControllerAdvice is @ControllerAdvice plus @ResponseBody, so every @ExceptionHandler method's return value is written to the response body (as JSON) instead of being treated as a view name. For REST APIs, use @RestControllerAdvice.

+Do I need spring.mvc.problemdetails.enabled if I extend ResponseEntityExceptionHandler?

No. The property only tells Spring Boot to register its own ResponseEntityExceptionHandler. If you declare your own advice that extends ResponseEntityExceptionHandler, Spring Boot's version backs off and yours handles the built-in exceptions.

+Why is my @RestControllerAdvice not catching exceptions?

The usual causes are: the advice class is outside the package scanned by @SpringBootApplication; the exception is thrown in a filter (such as Spring Security) before reaching a controller; or a more specific handler, possibly a local @ExceptionHandler in the controller, matches first.

+How do I return validation errors as JSON in Spring Boot?

Annotate the request body with @Valid, then override handleMethodArgumentNotValid in a class that extends ResponseEntityExceptionHandler, read the field errors from the BindingResult and add them to the ProblemDetail with setProperty.

+Should I return ProblemDetail or a custom ErrorResponse DTO?

For new APIs, ProblemDetail is the better default: it follows the RFC 9457 standard, Spring's built-in exceptions already use it, and you can still add custom fields. A custom DTO makes sense only if clients already depend on an existing error format.

+Does this work on Spring Boot 3?

Yes. ProblemDetail, ErrorResponse and the ResponseEntityExceptionHandler pattern arrived in Spring Framework 6.0 (Spring Boot 3.0). The code in this guide uses only those APIs, so it works on Spring Boot 3.x and 4.x.

Sources & references

  1. Spring Framework Reference (7.1) — Error Responses
  2. Spring Framework Reference — Exceptions (@ExceptionHandler)
  3. Spring Framework Reference — Controller Advice
  4. IETF — RFC 9457: Problem Details for HTTP APIs (July 2023)
  5. Spring Blog — Spring Boot 4.0.0 available now (20 Nov 2025)
  6. Spring Blog — Spring Boot 4.1.1 available now (20 Aug 2026)

Spotted an error? See our Corrections Policy.

  • #java
  • #spring-boot
  • #exception-handling
  • #rest-api
  • #problemdetail
Dipak Suryawanshi

Dipak SuryawanshiFounder & Editor

Dipak Suryawanshi is a backend developer who works with Java and Spring Boot, focused on building APIs, clean architectures and developer tools. He founded KernelBrief, an independent technology publication based in India, sets its editorial direction and is responsible for everything published on it. Every KernelBrief article is researched and checked against primary sources such as official documentation, vendor advisories and release notes before it is published.