Spring / Spring7 Intermediate to Advanced Interview questions
What is the difference between @ControllerAdvice and a Filter for handling errors in Spring MVC?
@ControllerAdvice paired with @ExceptionHandler operates inside the Spring MVC dispatch layer - it only catches exceptions thrown after HandlerMapping has already matched a controller and the request is being processed by, or on the way into, that controller's code (including argument resolution and interceptor logic). It works with typed model objects and has full access to Spring's HttpMessageConverters, so returning a structured JSON error body with the correct status code is straightforward.
| Aspect | @ControllerAdvice | Filter |
| Runs | Inside MVC dispatch | At the servlet container level, before DispatcherServlet |
| Catches | Exceptions from controller code | Anything, including requests that never reach a controller |
| Works with | Typed model objects, message converters | Raw HttpServletRequest/Response |
A Filter runs earlier and more broadly, wrapping DispatcherServlet itself, so it can intercept problems that never reach a controller at all - a malformed request a security filter rejects, or an exception thrown by another filter. In practice, the two are complementary: use @ControllerAdvice to translate business and validation exceptions into consistent structured error responses, and use filters for cross-cutting infrastructure concerns - authentication failures, request logging, global CORS handling - that need to run whether or not a controller handler was ever reached.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
