"@ControllerAdvice" and "@RestControllerAdvice"

When several controllers need the same exception response, local @ExceptionHandler methods create duplication. @ControllerAdvice moves those handlers into a separate component that Spring applies across controllers. @RestControllerAdvice is the REST-oriented variant: its handler results are written as response bodies by default.

Spring MVC exception flow

One global boundary

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(UserNotFoundException.class)
    ResponseEntity<ErrorResponse> notFound(
            UserNotFoundException ex, HttpServletRequest request) {
        return response(HttpStatus.NOT_FOUND, "USER_NOT_FOUND", ex, request);
    }

    @ExceptionHandler(ValidationException.class)
    ResponseEntity<ErrorResponse> validation(
            ValidationException ex, HttpServletRequest request) {
        return response(HttpStatus.BAD_REQUEST, "VALIDATION_ERROR", ex, request);
    }

    private ResponseEntity<ErrorResponse> response(
            HttpStatus status, String code, Exception ex, HttpServletRequest request) {
        return ResponseEntity.status(status)
            .body(new ErrorResponse(code, ex.getMessage(), request.getRequestURI()));
    }
}

The advice should translate errors, not contain business rules. Controllers stay focused on request mapping, services own domain decisions, and advice owns the public error format. Use one DTO shape for all handlers, but choose codes and statuses according to the meaning of each exception.

Component Responsibility
service Detect and name a domain failure
controller Map a valid request to a use case
@RestControllerAdvice Map exceptions to safe JSON
logger Preserve diagnostic details internally

Scope and fallback

An advice can be global or limited with basePackages, assignableTypes, or annotations. Start with one global advice for a small application. Add a final handler for unexpected exceptions that logs the full cause and returns a generic 500 response. The client must not learn the SQL statement, stack trace, or class name.

Do not create several competing global advices without a reason. Their order can affect which handler runs. Keep response construction consistent and test the result at the HTTP boundary, not only by calling handler methods directly.

Glossary
bytecode
Platform-independent compiled code that the JVM can execute.
class
A blueprint that defines fields and methods for objects in object-oriented programming.
object
A runtime instance of a class with its own state and behavior.
method
A named block of behavior that belongs to a class or object and can be called by code.
field
A variable stored inside a class or object that represents part of its state.
constructor
A special method-like block used to create and initialize a new object.
package
A namespace that groups related Java classes and helps organize code.
interface
A contract that defines methods a class can implement without prescribing all internal details.
generics
A language feature that lets code work with types as parameters while preserving type safety.
type erasure
The Java compiler process that removes most generic type details from runtime bytecode.
collection
A data structure that stores a group of elements and provides operations over them.
list
An ordered collection where elements have positions and duplicates are allowed.
set
A collection that stores unique elements and is commonly used for membership checks.
map
A key-value data structure where each key points to a value.
queue
A collection designed for processing elements in a defined order, often first-in-first-out.
lambda
A compact function-like expression used to pass behavior as data.
functional interface
An interface with one abstract method, suitable for lambdas and method references.
stream
A Java API for processing data sequences with operations such as map, filter, and reduce.
optional
A container object that represents a value that may or may not be present.
thread
An independent path of execution inside a running program.
synchronization
Coordination that protects shared data when multiple threads access it.
heap
The runtime memory area where Java objects are allocated.
stack
The runtime memory area that stores method calls, local variables, and call frames.
garbage collector
A JVM component that automatically frees memory occupied by objects no longer reachable.
memory leak
A situation where memory remains occupied because objects are still referenced but no longer useful.