Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Exceptions like ServletRequestBindingException in Spring rather than Servlet Container

I am using springmvc for a REST project and whenever the client calls a rest resource with the wrong HTTP method, a servletrequestbindingexception is thrown. I cannot handle these exceptions with a @ExceptionHandler in the controller, as it happens not within the handler method but in the spring mapping layer.

Currently I declared a web.xml exception handling, this works:

<error-page>
    <exception-type>org.springframework.web.bind.ServletRequestBindingException</exception-type>
    <location>/servletRequestBindingException.jsp</location>
</error-page>
<error-page>
    <error-code>405</error-code>
    <location>/methodNotSupported.jsp</location>
</error-page>

I'd rather use spring exception handling though. For example I'd like to create a dynamic response based on teh incoming Accept header, so either writing out json or xml for a rest exception for example. The best would be to return an object from this handler that would automatically be converted to json or xml just like a normal dto returned from a handler.

Is there a way to catch these lower level mapping exceptions?

like image 377
Sven Haiges Avatar asked Apr 11 '26 09:04

Sven Haiges


1 Answers

You can't use @ExceptionHandler (since as you say, this is for dealing exceptions thrown from within the handler code), but you can still use the HandlerExceptionResolver framework to do this.

By default, DispatcherServlet registers an instance of DefaultHandlerExceptionResolver:

Default implementation of the HandlerExceptionResolver interface that resolves standard Spring exceptions and translates them to corresponding HTTP status codes.

The generation of the HTTP 405 is actually handled in this class, by catching HttpRequestMethodNotSupportedException thrown by the handler-mapping code.

So if you want to handle this exception differently, you can provide your own implementation of HandlerExceptionResolver. It's probably easiest to subclass DefaultHandlerExceptionResolver and override the handleHttpRequestMethodNotSupported method, returning your ModelAndView from there.

like image 140
skaffman Avatar answered Apr 13 '26 21:04

skaffman