Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exceptions thrown in Filters?

I am using Spring 4 and Tomcat. The issue is sometimes I have to throw a (custom) RuntimeException in my filter (The control has not even reached the controller). The issue is since I am not throwing an exception that tomcat understands, it gets converted to 500 (internal server error). I believe a 403 Forbidden would be better than a 500 (For my custom exception). I have looked at @ExceptionHandler and @ControllerAdvice annotations. But these work only if the control reaches the controller.

As of now I am manually setting the status to 403 in the HTTPResponse in my filter. Is there a better way of handling this scenario?

like image 340
TheLostMind Avatar asked Sep 16 '15 05:09

TheLostMind


People also ask

How do you manage exceptions thrown in filters in spring boot?

Spring security exceptions can be directly handled by adding custom filters and constructing the response body. To handle these exceptions at a global level via @ExceptionHandler and @ControllerAdvice, we need a custom implementation of AuthenticationEntryPoint.

How do you handle thrown exceptions?

The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.

What is the meaning of filter threw exception?

If there is an exception thrown within the filter, then that exception will be silently swallowed and the filter simply fails. This causes the original exception to go down the catch cases or ultimately end up being reraised upwards.

What are the 3 blocks used to handle exception?

The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later. The "finally" block is used to execute the necessary code of the program.


1 Answers

you should use something like this

Setting an error handler in web.xml

<error-page>
    <exception-type>java.lang.RuntimeException</exception-type>
    <location>/handleExceptionService</location>
</error-page>

So, when you reach your service, yo can do wathever you want with the error.

Good Luck!!!

like image 197
Jairo Cordero Avatar answered Oct 19 '22 02:10

Jairo Cordero