Through the documentation of spring framework, I got to know about customizing exception handling mechanism of spring application. As per the documentation, It is stated that spring provides some default exception Resolvers.
SimpleMappingExceptionResolver
A mapping between exception class names and error view names. Useful for rendering error pages in a browser application.
DefaultHandlerExceptionResolver
Resolves exceptions raised by Spring MVC and maps them to HTTP status codes. See also alternative ResponseEntityExceptionHandler and REST API exceptions.
ResponseStatusExceptionResolver
Resolves exceptions with the @ResponseStatus annotation and maps them to HTTP status codes based on the value in the annotation.
ExceptionHandlerExceptionResolver
Resolves exceptions by invoking an @ExceptionHandler method in a @Controller or a @ControllerAdvice class. See @ExceptionHandler methods.
But in my requirement, I do not want the support of all these resolvers I just want ExceptionHandlerExceptionResolver to handle the exception in my Spring Application. So for that, I have added the following Configuration in my DispatcherServlet.
DispatcherServlet related configuration.
public void onStartup(ServletContext servletCxt) throws { ServletException {
......
dServlet.setDetectAllHandlerExceptionResolvers(false);
dServlet.setThrowExceptionIfNoHandlerFound(false);
.....
}
And in my Bean configuration java class, I have created following bean.
@Bean(name=DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME)
HandlerExceptionResolver customExceptionResolver ( ) {
return new ExceptionHandlerExceptionResolver();
}
In the documentation, it is stated that
/** * Set whether to detect all HandlerExceptionResolver beans in this servlet's context. Otherwise, * just a single bean with name "handlerExceptionResolver" will be expected. *
Default is "true". Turn this off if you want this servlet to use a single * HandlerExceptionResolver, despite multiple HandlerExceptionResolver beans being defined in the context. */
But even after all such configuration, I see HTML error pages and not JSON error response.
Sample ExceptionHandler method.
@ExceptionHandler(value={NullPointerException.class})
public ResponseEntity<Object> nullPointerExceptionHandler(NullPointerException e){
logger.info("local exception resolver running");
Map<String,Object> map=new HashMap<String,Object>(6);
map.put("isSuccess",false);
map.put("data",null);
map.put("status",HttpStatus.INTERNAL_SERVER_ERROR);
map.put("message", e.getMessage());
map.put("timestamp",new Date());
map.put("fielderror",null);
return new ResponseEntity<Object>(map,HttpStatus.BAD_GATEWAY);
}
What I am doing wrong? I only need the support of ExceptionHandlerExceptionResolver throughout my spring application to maintain consitency.