Scrivio Interview library
DebuggingIntermediate5 min read · updated 12 November 2026

Two @RestControllerAdvice classes exist: one in a shared library handling Exception and one in the service handling OrderNotFoundException. Sometimes the library's generic 500 response is returned for OrderNotFoundException. Why?

Spring checks advice beans one at a time in their order, and it uses the first advice that has any handler matching the exception. The closest-type rule applies only inside one advice. The library's handler for Exception matches OrderNotFoundException, so whenever the library advice comes first, it wins with a generic 500. Both advices probably have no @Order, which makes their relative order depend on bean registration, hence sometimes. The fix is an explicit order: higher priority for the service advice, the lowest for the library's catch-all.

Why this question is asked

This bug is confusing because it breaks an intuition. We learned that Spring picks the closest matching exception handler, and here a handler for OrderNotFoundException exists, yet the generic one for Exception wins. It also comes and goes, which suggests a race or a cache. The real cause is simpler and deterministic once we know the algorithm. Interviewers ask it because it tests whether we know how ExceptionHandlerExceptionResolver searches advices, and because shared libraries with catch-all handlers are common. In this answer, we will reproduce the setup, look at how Spring searches advices, explain the sometimes, fix it, and set a rule for libraries.

1Reproducing the Setup

The shared library ships an advice with a catch-all handler, and the service adds its own advice for its domain exception. Neither declares an order.

Java
// in the shared library jar
@RestControllerAdvice
public class CommonErrorAdvice {
@ExceptionHandler(Exception.class)
ProblemDetail any(Exception ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "Unexpected error");
}
}
// in the order service
@RestControllerAdvice
class OrderErrorAdvice {
@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail notFound(OrderNotFoundException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
}
}
// GET /orders/42 -> sometimes 404 from OrderErrorAdvice, sometimes 500 from CommonErrorAdvice

Notice that both handlers really do match. OrderNotFoundException is an Exception, so the library's handler is a valid choice, just not the one we meant.

2How Spring Searches the Advices

ExceptionHandlerExceptionResolver, the part of Spring MVC that runs @ExceptionHandler methods, first looks in the controller that threw. If nothing matches there, it goes through the advice beans in a sorted list. For each advice it asks: do you have any handler for this exception type? Inside that advice it picks the closest type, but as soon as one advice answers yes, the search stops.

Step throughLibrary advice first in the list
DispatcherServletResolverCommonErrorAdviceOrderErrorAdvice
resolve OrderNotFoundException
no handler in OrderController
any handler for this type?
yes: any(Exception)
500 Unexpected error

5 messages in order. Play them, or step through them one at a time.

OrderErrorAdvice is never asked, although it has the better match.

So the closest-match rule is per advice, not global. The search never compares the library's Exception handler with the service's OrderNotFoundException handler, because they live in different advices. Whichever advice is earlier in the list decides.

3Why It Happens Only Sometimes

The list of advices is sorted by order: the @Order annotation, the Ordered interface or @Priority. An advice without any of them gets the lowest precedence, Ordered.LOWEST_PRECEDENCE. Here both advices have that same value, so the sort has no basis to put one before the other, and they stay in the order in which their beans were registered.

Registration order is not something we control or should rely on. It depends on whether the library advice is picked up by component scanning or by auto-configuration, on the order of packages being scanned, and on the classpath. A small change, a new dependency, a different build tool, a test slice that loads beans differently, can flip it. That is why one environment returns 404 and another 500, or why it changes after an unrelated upgrade. The behaviour is deterministic for a given setup but fragile across setups.

4Fixing It With an Explicit Order

We make the order explicit on both sides. The service advice gets a higher priority, which in Spring means a lower order value, and the library advice is pinned to the lowest precedence.

Java
// service
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE) // or any value lower than the library's, such as 0
class OrderErrorAdvice { ... }
// library
@RestControllerAdvice
@Order(Ordered.LOWEST_PRECEDENCE)
public class CommonErrorAdvice { ... }
// GET /orders/42 -> 404 from OrderErrorAdvice, every time
// GET /orders/boom -> IllegalStateException -> 500 from CommonErrorAdvice

Notice that the annotation on the library alone is not enough. The library's value equals the default, so an unordered service advice would still tie with it. The service advice must declare an order, or the library must document that teams set one. To guard the fix, we add a web test that throws OrderNotFoundException and asserts a 404, so a future change in bean order fails the build instead of reaching production.

5The Rule for Libraries

Any shared library that ships a catch-all handler should give it the lowest precedence explicitly and should register it through auto-configuration with a property to switch it off, so a service can opt out completely. Better still, the library separates two things: an advice that handles standard Spring exceptions and the catch-all, at the lowest precedence, and a documented extension point for domain exceptions, such as a base exception type with its own status and code, which the library maps itself. Then most services do not need a second advice at all, and the conflict cannot arise.

6Follow-up questions

Would putting both handlers in one advice also fix it?

Yes. Inside one advice Spring compares all matching handlers and picks the closest type, so OrderNotFoundException would go to the specific handler. But the library and the service are separate code bases, so merging is rarely practical. Ordering is the general fix.

How can we see the actual order of advices at runtime?

We can log the result of ControllerAdviceBean.findAnnotatedBeans(context) at startup, which returns the advice beans sorted the way Spring will use them, or we can set a breakpoint in ExceptionHandlerExceptionResolver and look at its advice cache. A test that asserts the status for each domain exception is the practical safeguard.

Why not let the library's catch-all inspect the exception and delegate?

That couples the library to every service's exceptions or forces it to guess with reflection. Clear precedence, a base exception type the library understands and service-level handlers with higher priority keep responsibilities separate and predictable.

7Conclusion

In this answer, we saw that ExceptionHandlerExceptionResolver asks advices in order and uses the first one with any matching handler, and that the closest-match rule applies only within one advice. The library's Exception handler matched first whenever its advice was registered first, which varied because neither advice declared an order. We fixed it with an explicit higher priority on the service advice and the lowest precedence on the library's catch-all, added a test, and set a rule that libraries keep catch-alls at the lowest precedence with an off switch.

What to say in the interviewAbout 80 seconds aloud

Open with

The key is how Spring searches advices. ExceptionHandlerExceptionResolver first checks the controller, then goes through the advice beans in sorted order, and it stops at the first advice that has any handler matching the exception.

Then, if they want more

The closest-type rule only applies inside one advice. The library's handler for Exception matches OrderNotFoundException, so if the library advice comes first in the list, it wins with its generic 500, and the service's specific handler is never even considered.

The sometimes comes from ordering: neither advice has @Order, so both get the lowest precedence, and with equal values they stay in bean registration order. That depends on scanning, auto-configuration and the classpath, so it can differ between environments or flip after an unrelated change. The fix is an explicit order.

I'd give the service advice @Order of HIGHEST_PRECEDENCE or at least something lower than the library's, and make the library declare LOWEST_PRECEDENCE for its catch-all. Just annotating the library isn't enough, since an unordered service advice would still tie. I'd add a web test asserting 404 for that exception.

And as a rule, libraries should keep catch-all handlers at the lowest precedence and let services switch them off.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Two @RestControllerAdvice classes exist: one in a shared library handling Exception and...": https://scrivio-interview-library.netlify.app/spring-boot/error-handling/ba9412bc92/