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?
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.
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.
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.
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.
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!!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With