11

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?

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • 1
    Check out [this SO post](http://stackoverflow.com/questions/29914717/servlet-filter-specific-exception-handling-in-java). You can extend the filter and handle the exception in super. – Tim Biegeleisen Sep 16 '15 at 05:26
  • @TimBiegeleisen - Well, as of now I am following a similar approach :). Thank you for pointing to that post. – TheLostMind Sep 16 '15 at 05:30
  • @TimBiegeleisen I came across a similar issue, and posted a solution that might interest you in here https://stackoverflow.com/questions/34595605/how-to-manage-exceptions-thrown-in-filters-in-spring/43242424 – Raf Apr 05 '17 at 22:11

2 Answers2

1

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!!!

Jairo Cordero
  • 640
  • 6
  • 8
0
You can add in web.xml
<error-page>
    <error-code>404</error-code> 
    <location>/error-404.html</location>
</error-page> 
<error-page>
    <error-code>403</error-code> 
    <location>/access_denied.html</location>
</error-page>