Skip to content
Spring MVC @ControllerAdvice: Exception Matching Order, Coverage Scope & Source-Code Deep Dive

Spring MVC @ControllerAdvice: Exception Matching Order, Coverage Scope & Source-Code Deep Dive

This article explains how Spring MVC's @ControllerAdvice selects exception handlers by inheritance depth, how @Order prioritizes multiple advice classes, which scope attributes limit coverage, and why Filter exceptions, 404 errors, and afterCompletion interceptor exceptions escape global handling.

Java Tech Workshop
Java Tech Workshop
Java Tech Workshop

How Exceptions Reach @ExceptionHandler

Spring MVC's DispatcherServlet delegates exception handling to a chain of HandlerExceptionResolver implementations. The key resolver for @ExceptionHandler is ExceptionHandlerExceptionResolver.

DispatcherServlet.doDispatch()
  ↓ Controller throws exception
processHandlerException()
  ↓ Iterates HandlerExceptionResolver chain
ExceptionHandlerExceptionResolver
  ↓ Looks up @ExceptionHandler methods
Your @ControllerAdvice handler methods

Two Types of Exception Handlers

@ExceptionHandler

can be placed in two locations:

// ① Inside a Controller: handles only that Controller's exceptions
@RestController
@RequestMapping("/order")
public class OrderController {
    @ExceptionHandler(OrderException.class)
    public Result<?> handle(OrderException e) { ... }
}

// ② Inside @ControllerAdvice: global handling (scope can be limited)
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public Result<?> handle(Exception e) { ... }
}

Matching rule: handlers inside the current Controller take priority over global Advice. This is the first priority rule.

Each Handler Gets Its Own Resolver

ExceptionHandlerExceptionResolver

creates an ExceptionHandlerMethodResolver for each Controller and each @ControllerAdvice. This resolver maintains the mapping from exception type to handler method.

Matching Order: How Multiple @ExceptionHandler Methods Are Selected

Rule: Most Specific Exception Wins

Given three handler methods:

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<?> handleIllegalArg(IllegalArgumentException e) { ... }

    @ExceptionHandler(RuntimeException.class)
    public Result<?> handleRuntime(RuntimeException e) { ... }

    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e) { ... }
}

Throwing new IllegalArgumentException("xxx") — its inheritance chain:

IllegalArgumentException
  extends RuntimeException
    extends Exception

The call always goes to handleIllegalArg. Rule: find the handler whose exception type has the shortest inheritance distance to the thrown exception; more specific types have higher priority.

Source Code: ExceptionHandlerMethodResolver

The resolver's resolveMethod looks up the handler:

// Spring MVC source (simplified)
public class ExceptionHandlerMethodResolver {
    private final Map<Class<? extends Throwable>, Method> mappedMethods = new HashMap<>();

    public Method resolveMethod(Exception exception) {
        Method method = resolveMethodByExceptionType(exception.getClass());
        if (method == null) {
            Throwable cause = exception.getCause();
            if (cause != null) {
                method = resolveMethodByExceptionType(cause.getClass());
            }
        }
        return method;
    }

    private Method resolveMethodByExceptionType(Class<? extends Throwable> exceptionType) {
        Method method = this.exceptionLookupCache.get(exceptionType);
        if (method == null) {
            method = getMappedMethod(exceptionType);
            this.exceptionLookupCache.put(exceptionType, method);
        }
        return method;
    }
}

Core: ExceptionDepthComparator

getMappedMethod

uses ExceptionDepthComparator to sort candidate types:

private Method getMappedMethod(Class<? extends Throwable> exceptionType) {
    List<Class<? extends Throwable>> matches = new ArrayList<>();
    for (Class<? extends Throwable> mappedException : this.mappedMethods.keySet()) {
        if (mappedException.isAssignableFrom(exceptionType)) {
            matches.add(mappedException); // collect all matching (parent/self)
        }
    }
    if (!matches.isEmpty()) {
        if (matches.size() > 1) {
            matches.sort(new ExceptionDepthComparator(exceptionType));
        }
        return this.mappedMethods.get(matches.get(0));
    }
    return null;
}
ExceptionDepthComparator

calculates the inheritance depth from the candidate type to the actual thrown type:

// Depth calculation: walk up the thrown exception's inheritance chain, count levels
private int getDepth(Class<?> exceptionType, int depth) {
    if (exceptionType == this.targetException) {
        return depth; // exact match, depth 0
    }
    for (Class<?> ifc : exceptionType.getInterfaces()) {
        int result = getDepth(ifc, depth + 1);
        if (result != -1) return result;
    }
    Class<?> superClass = exceptionType.getSuperclass();
    if (superClass == null) return -1;
    return getDepth(superClass, depth + 1); // each level up adds 1
}

For IllegalArgumentException: IllegalArgumentException depth 0 RuntimeException depth 1 Exception depth 2

Smallest depth wins. Results are cached in exceptionLookupCache for subsequent hits.

Two Handlers at Same Depth

If two @ExceptionHandler methods target exception types at the same inheritance depth (ambiguous), Spring throws IllegalStateException at startup. Avoid ambiguous mappings.

Coverage Scope: Which Controllers Does @ControllerAdvice Apply To?

Many assume @ControllerAdvice applies globally by default, but its scope is precisely controllable via four attributes:

// Package scope: only Controllers under this package
@ControllerAdvice(basePackages = "com.demo.order.controller")
public class OrderAdvice { ... }

// Type scope: only the specified class or its subclasses
@ControllerAdvice(assignableTypes = OrderController.class)
public class OrderAdvice { ... }

// Annotation scope: only Controllers bearing this annotation
@ControllerAdvice(annotations = RestController.class)
public class RestAdvice { ... }

// No attributes: global, applies to all Controllers
@ControllerAdvice
public class GlobalAdvice { ... }
value

/ basePackages — Restrict by package path basePackageClasses — Use a class's package as scope (type-safe) assignableTypes — Restrict to specific Controller types annotations — Restrict to Controllers with a given annotation

Layered Design: Module-Specific + Global Fallback

Using scope attributes enables layered exception handling:

// Order module: handles order-specific exceptions
@RestControllerAdvice(basePackages = "com.demo.order")
public class OrderModuleAdvice {
    @ExceptionHandler(OrderException.class)
    public Result<?> handleOrder(OrderException e) {
        return Result.fail(e.getCode(), e.getMessage());
    }
}

// Global fallback: handles common exceptions for all modules
@RestControllerAdvice
public class GlobalAdvice {
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e) {
        return Result.fail(500, "System busy");
    }
}

@RestControllerAdvice vs @ControllerAdvice

@ControllerAdvice
@ResponseBody
public @interface RestControllerAdvice { ... }
@RestControllerAdvice

= @ControllerAdvice + @ResponseBody. Return values are written directly to the response body. Matching order and scope rules are identical.

Priority Between Multiple @ControllerAdvice Classes

Rule: @Order Determines Sequence

When multiple Advice classes can handle the same exception, Spring uses @Order:

@Order(1) // smaller number = higher priority
@RestControllerAdvice
public class FirstAdvice {
    @ExceptionHandler(Exception.class)
    public Result<?> handle(Exception e) { ... }
}

@Order(2)
@RestControllerAdvice
public class SecondAdvice {
    @ExceptionHandler(Exception.class)
    public Result<?> handle(Exception e) { ... }
}
ExceptionHandlerExceptionResolver

collects all Advice beans at startup, sorts them by @Order, and at runtime iterates in that order. The first Advice that can resolve the exception is used; subsequent ones are not consulted.

Complete Priority Chain

Combining all rules, the full matching sequence for an incoming exception is:

① Current Controller's @ExceptionHandler (highest priority)
    ↓ if none
② Iterate all @ControllerAdvice in @Order order
    ↓ within each Advice
③ Select handler by exception inheritance depth (most specific)
    ↓ if none
④ Delegate to next HandlerExceptionResolver / default error handling

Verifiable Example

@Order(1)
@RestControllerAdvice
public class ModuleAdvice {
    @ExceptionHandler(BusinessException.class)
    public Result<?> handleBiz(BusinessException e) {
        return Result.fail(e.getCode(), "Module handling");
    }
}

@Order(2)
@RestControllerAdvice
public class GlobalAdvice {
    @ExceptionHandler(Exception.class)
    public Result<?> handleAll(Exception e) {
        return Result.fail(500, "Global handling");
    }
}

Throw BusinessException: ModuleAdvice is first in order and can handle it → used.

Throw NullPointerException: ModuleAdvice cannot handle → falls through to GlobalAdvice → handleAll used.

Coverage Boundaries: Exceptions @ControllerAdvice Cannot Catch

@ControllerAdvice

only operates on exceptions thrown inside the DispatcherServlet's Controller execution chain . Anything outside that boundary is invisible to it.

Filter Exceptions: Not Caught

Filters execute before DispatcherServlet; their exceptions never enter the MVC chain:

@Component
public class AuthFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp,
            FilterChain chain) {
        throw new RuntimeException("Auth failed"); // @ControllerAdvice cannot catch
    }
}

Solution: catch inside the Filter and write the response manually:

@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp,
        FilterChain chain) throws ServletException, IOException {
    try {
        chain.doFilter(req, resp);
    } catch (BusinessException e) {
        resp.setStatus(HttpStatus.OK.value());
        resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
        resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
        resp.getWriter().write(JSON.toJSONString(Result.fail(e.getCode(), e.getMessage())));
    }
}

404 Errors: Bypass Global Handler by Default

When no handler is found, Spring MVC does not throw an exception into @ExceptionHandler. Instead, the Servlet container and Spring Boot's BasicErrorController handle it via /error.

To make 404s reach the global handler, enable:

spring:
  mvc:
    throw-exception-if-no-handler-found: true # throws NoHandlerFoundException
  web:
    resources:
      add-mappings: false # disable default static resource mapping

Then catch it:

@ExceptionHandler(NoHandlerFoundException.class)
public Result<?> handle404(NoHandlerFoundException e) {
    return Result.fail(404, "Endpoint not found");
}

Interceptor Exceptions: Phase-Dependent

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(...) {
        throw new BusinessException(401, "Unauthenticated"); // caught by @ControllerAdvice
    }

    @Override
    public void postHandle(...) {
        throw new RuntimeException(); // caught
    }

    @Override
    public void afterCompletion(...) {
        throw new RuntimeException(); // only logged, not handled
    }
}
preHandle

and postHandle exceptions bubble up to DispatcherServlet 's exception handling and are caught. afterCompletion runs after view rendering; its exceptions are only logged.

Exception Handler Throwing Another Exception

If an @ExceptionHandler method itself throws an exception, it is not recursively handled by the same Advice. The exception propagates upward and is ultimately handled by the container error page or BasicErrorController. Handler methods must be robust; wrap risky code in try-catch if needed.

Special Built-In Exception: ResponseStatusException

@GetMapping("/{id}")
public OrderVO get(@PathVariable Long id) {
    Order order = orderService.get(id);
    if (order == null) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Order not found");
    }
    return convert(order);
}
ResponseStatusException

can be caught by @ExceptionHandler for unified wrapping, or left alone to let Spring respond with the specified HTTP status.

Understanding @ControllerAdvice matching order and coverage scope is essential for backend engineering and senior-level interviews. Mastering these mechanics enables precise debugging of "exception not caught", "wrong handler selected", and "404 not unified" issues. Follow-up topics include the full HandlerExceptionResolver chain, unified validation exception handling, BasicErrorController internals, and Filter exception fallback strategies.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Exception HandlingSpring MVC@Order@ControllerAdvice@ExceptionHandlerExceptionDepthComparatorExceptionHandlerExceptionResolverNoHandlerFoundException
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.