在春季自定义ExceptionResolver时发生意外行为

时间:2018-10-21 12:35:38

标签: java spring spring-boot handlerexceptionresolver

通过spring框架的文档,我了解了有关定制spring应用程序的异常处理机制的知识。根据文档,据说spring提供了一些默认的异常解析器。

SimpleMappingExceptionResolver

异常类名称和错误视图名称之间的映射。对于在浏览器应用程序中呈现错误页面很有用。

DefaultHandlerExceptionResolver

解决Spring MVC引发的异常并将其映射到HTTP状态代码。另请参见其他ResponseEntityExceptionHandler和REST API异常。

ResponseStatusExceptionResolver

使用@ResponseStatus批注解决异常,并根据批注中的值将其映射到HTTP状态代码。

ExceptionHandlerExceptionResolver

通过调用@Controller或@ControllerAdvice类中的@ExceptionHandler方法来解决异常。请参阅@ExceptionHandler方法。

但是在我的需求中,我不想要所有这些解析器的支持,我只希望ExceptionHandlerExceptionResolver处理我的Spring Application中的异常。为此,我在DispatcherServlet中添加了以下配置。

DispatcherServlet 相关配置。

       public void onStartup(ServletContext servletCxt) throws   {                   ServletException {
             ......
    dServlet.setDetectAllHandlerExceptionResolvers(false);
    dServlet.setThrowExceptionIfNoHandlerFound(false);
             .....
  }

在我的Bean配置Java类中,我创建了以下bean。

      @Bean(name=DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME)
         HandlerExceptionResolver customExceptionResolver ( ) {
    return new ExceptionHandlerExceptionResolver();
}

文档中指出

/ **      *设置是否在此servlet的上下文中检测所有HandlerExceptionResolver bean。除此以外,      *只需要一个名称为“ handlerExceptionResolver”的bean。      *

默认为“ true”。如果您希望此servlet使用单个      * HandlerExceptionResolver,尽管在上下文中定义了多个HandlerExceptionResolver bean。      * /

但是即使进行了所有此类配置,我仍然看到HTML错误页面,而不是JSON错误响应。

示例ExceptionHandler方法。

       @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);
    }

我做错了什么?我仅在整个Spring应用程序中都需要ExceptionHandlerExceptionResolver的支持才能保持一致性。

0 个答案:

没有答案