简体   繁体   中英

Capture Spring MVC DispatcherServlet exceptions with ExceptionResolver

I am trying to return a valid JSON body for every request of an Spring MVC service, both correct and invalid.

Using @ExceptionHandler and a combination of ExceptionHandlerExceptionResolver , DefaultHandlerExceptionResolver and my own AbstractHandlerExceptionResolver I am able to process and set a body for almost all invalid requests that are dispatched to a valid controller or rejected by Spring Security.

However, errors thrown by the DispatcherServlet like noHandlerFound , can't be intercepted, so the response has a valid HTTP status code like 404, but the body contains the Tomcat default XML error.

Anybody knows how to set up or configure an Spring Exception Resolver so all failed requests are intercepted and a valid JSON body could be set?

There is a section explaining how is spring handling exception resolver for dispatcher servlet. [ http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html][1]

The dispatcher's exception resolution strategy can be specified via a HandlerExceptionResolver, for example mapping certain exceptions to error pages. Default are AnnotationMethodHandlerExceptionResolver, ResponseStatusExceptionResolver, and DefaultHandlerExceptionResolver. These HandlerExceptionResolvers can be overridden through the application context. HandlerExceptionResolver can be given any bean name (they are tested by type).

to be able to support Dispatcher exception handling overriding you have to implement HandlerExceptionResolver and Ordered class and declare the implementation as spring bean. You must return getOrder value as Integer.MIN_VALUE to override any other existing handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM