# Global Exception Handling with @ControllerAdvice

> How do you handle exceptions globally in a Spring Boot REST API instead of writing try-catch in every controller?

Canonical: https://www.internhack.in/learn/interview/spring-boot-interview/spring-controlleradvice-global-exception-handling
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

How do you handle exceptions globally in a Spring Boot REST API instead of writing try-catch in every controller?

## Answer

Picture a hospital with no central emergency desk, where every ward improvises how to handle a crisis. That is what an API looks like when each controller catches its own exceptions: inconsistent status codes, different JSON shapes, and stack traces leaking to clients. Global exception handling is the emergency desk. You define one place that translates every exception into a predictable HTTP response.

The mechanism is @ControllerAdvice, or @RestControllerAdvice, which is @ControllerAdvice plus @ResponseBody. It marks a class whose methods apply across all controllers. Inside, each method annotated with @ExceptionHandler declares which exception types it handles, and returns a response. When a controller throws, Spring's HandlerExceptionResolver infrastructure, specifically ExceptionHandlerExceptionResolver, looks for the most specific matching handler and invokes it, so a handler for ResourceNotFoundException wins over one for RuntimeException.

A good design has several layers. Define a small hierarchy of domain exceptions, for example ResourceNotFoundException mapping to 404, DuplicateResourceException mapping to 409, and BusinessRuleException mapping to 422 or 400. Throw them from the service layer, where the business knowledge lives, and translate to HTTP only in the advice, so services never need to know about status codes. Add handlers for framework exceptions too: MethodArgumentNotValidException for validation, HttpMessageNotReadableException for bad JSON, and AccessDeniedException for authorisation. Finish with a catch-all handler for Exception that logs the full stack trace with a correlation id and returns a generic 500 message. Never send the stack trace or SQL details back, since that leaks internals.

Response shape matters. Choose a consistent structure with timestamp, status, error code, message, and path, and use the same for every error. Spring 6 and Boot 3 also support RFC 7807 Problem Details through the ProblemDetail class and the property spring.mvc.problemdetails.enabled=true, giving a standard application/problem+json format that clients and API gateways understand. You can extend ResponseEntityExceptionHandler to inherit sensible handling for the many built-in MVC exceptions and override only what you need.

Limits worth knowing: @ControllerAdvice handles exceptions thrown from controllers. Exceptions from servlet filters, such as a failing JWT filter in Spring Security, occur before the DispatcherServlet and bypass the advice, so they need an AuthenticationEntryPoint or a filter-level handler. Also remember the difference between @ResponseStatus on an exception class, which is a quick option for simple cases, and the advice approach, which offers full control.

You can scope an advice to certain controllers using basePackages, assignableTypes, or annotations, which helps in large codebases with separate public and admin APIs. In tests, @WebMvcTest loads the advice automatically, so you can assert error responses with MockMvc.

## Code examples

### Centralised handler with ProblemDetail

```
public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String resource, Object id) {
        super(resource + " not found with id " + id);
    }
}

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ProblemDetail notFound(ResourceNotFoundException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    }

    @ExceptionHandler(DataIntegrityViolationException.class)
    public ProblemDetail conflict(DataIntegrityViolationException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, "Duplicate or invalid data");
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> fallback(Exception ex) {
        String id = UUID.randomUUID().toString();
        log.error("Unhandled error {}", id, ex);              // full detail only in logs
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Map.of("error", "Internal error", "reference", id));
    }
}
```

Services throw domain exceptions; the advice alone decides the HTTP status and JSON shape.

## Key points

- Most specific exception handler wins.
- Filter-level exceptions bypass @ControllerAdvice and need an entry point or filter handler.
- Never expose stack traces or SQL errors to clients.
- Boot 3 supports RFC 7807 ProblemDetail out of the box.

## Common follow-up questions

- How do you handle exceptions thrown inside a security filter?
- What is ResponseEntityExceptionHandler?
- How do you attach a correlation id to error responses?

## Interview tips

- Explain the layering: domain exceptions in services, HTTP mapping in the advice.
- Point out the filter limitation to show real-world experience.

## Concepts covered

ControllerAdvice, ExceptionHandler, ProblemDetail, Error Handling

Previous: [Bean Validation with @Valid and @Validated](https://www.internhack.in/learn/interview/spring-boot-interview/spring-validation-valid) · Next: [ResponseEntity and Correct HTTP Status Codes](https://www.internhack.in/learn/interview/spring-boot-interview/spring-responseentity) · [All of Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)

## More Spring Boot questions

- [Spring Data JPA: Repositories, Derived Queries and @Query](https://www.internhack.in/learn/interview/spring-boot-interview/spring-data-jpa-repositories-queries)
- [JPA Relationships and the N+1 Query Problem](https://www.internhack.in/learn/interview/spring-boot-interview/spring-jpa-relationships-n-plus-one)
- [Lazy vs Eager Fetching and LazyInitializationException](https://www.internhack.in/learn/interview/spring-boot-interview/spring-jpa-lazy-vs-eager-fetching)
- [@Transactional: Propagation, Rollback Rules and Self-Invocation](https://www.internhack.in/learn/interview/spring-boot-interview/spring-transactional-pitfalls)
- [Hibernate First-Level and Second-Level Cache](https://www.internhack.in/learn/interview/spring-boot-interview/spring-hibernate-caching)
- [Spring Security Filter Chain and JWT Authentication Flow](https://www.internhack.in/learn/interview/spring-boot-interview/spring-security-filter-chain-jwt)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)
