Handle Custom Exceptions in Spring Security Handle Custom Exceptions in Spring Security spring spring

Handle Custom Exceptions in Spring Security


It's important to remember that the order of the filters in Spring Security matters.

From Spring Security 3 book:

The ExceptionTranslationFilter will be able to handle and react to only those exceptions that are thrown below it in the filter chain execution stack. Users often get confused, especially when adding custom filters in the incorrect order, as to why the expected behavior differs from their application's actual exception handling—in many of these cases, the order of the filters is to blame!

If your filters are about authorization it is a good practice to put them a the end of the chain as this approach is used by default authorization filters. That way you don't have to reinvent the wheel.

Standard filters: Table in documentation

After you properly configured your filter chain, you can configure error page, or even custom handler. More information available in documentation.


I see that ExceptionTranslationFilter only handles two exceptions AuthenticationException and AccessDeniedException with custom handlers for these two exceptions, what about any other type of exception or even run time exceptions?

How would you handle/intercept just about any exception in Spring filter stack? Isn't there any Spring standard way to catch and get request (besides writing a custom filter on top of everything), response without writing another filter on top of everything?

<security:http auto-config="false" use-expressions="true"disable-url-rewriting="true" entry-point-ref="authenticationEntryPoint"pattern="/**"><security:custom-filter before="FIRST" ref="stackExceptionFilter" /><security:custom-filter before="..." ref="authenticationFilter" /><security:logout /></security:http> 

Well, I ended up adding another filter right on top (or configure the filter for /* in web.xml) that simply had try catch block and delegated any uncaught exception to a custom exception handler Spring component calling an ExceptionController method (each method returning different response type in different ways) in a fail safe way also returning custom exception messages based on exception type (our requirement). The only down part was to add some logic so you won't keep looping. The Spring custom ExceptionHandlerExceptionResolver and @ExceptionHandler in controllers do not handle filter exceptions and have limitation on how you want to return an exception message as (XML/JSON, redirect, forward,....). This assumes you have good Application Exception hierarchy that catches exceptions and throws them with sensible reference information as filters don't have anything.

Same for error codes, define static pages in web.xml but do catch them by mapping a filter to the ERROR dispatcher and preparing model for the pages displaying the error code.