用于捕获错误的Spring ExceptionHandlerController无法正常工作

时间:2017-12-28 17:21:48

标签: java spring jsp model-view-controller

我正在尝试创建一个控制器,以便当用户转到不存在的URL时,他/她将被映射到自定义错误页面“error.jsp”。

目前,我的异常处理程序控制器如下所示:

@ControllerAdvice 
public class ExceptionHandlerController {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandlerController.class);

    @ExceptionHandler(value = {Exception.class, RuntimeException.class})
    public String defaultErrorHandler(Exception e) {
        logger.error("Unhandled exception: ", e);
        return "error";
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public String handle(Exception e) {
        logger.error("No handler found!", e);
        return "error";
    }
}

但是,当我运行我的网络应用并访问一个不存在的网址时,我会被重定向到默认的浏览器页面,上面写着'404这个网页不能是网页。

有没有人对为什么这不起作用有任何想法或建议?

1 个答案:

答案 0 :(得分:0)

来自NoHandlerFoundException

的javaDoc
  

默认情况下DispatcherServlet无法找到a的处理程序   请求它发送404响应。但是,如果它的财产   “throwExceptionIfNoHandlerFound”设置为true,此异常为   引发并可以使用已配置的HandlerExceptionResolver处理。

解决这个,你需要确保你做了 2件事

  1. 创建 SimpleMappingExceptionResolver 并注册为bean

    @Bean HandlerExceptionResolver customExceptionResolver () { SimpleMappingExceptionResolver s = new SimpleMappingExceptionResolver(); Properties p = new Properties(); //mapping spring internal error NoHandlerFoundException to a view name. p.setProperty(NoHandlerFoundException.class.getName(), "error-page"); s.setExceptionMappings(p); //uncomment following line if we want to send code other than default 200 //s.addStatusCode("error-page", HttpStatus.NOT_FOUND.value());

      //This resolver will be processed before default ones
      s.setOrder(Ordered.HIGHEST_PRECEDENCE);
      return s;
    

    }

    1. 在dispatcherServlet中将 setThrowExceptionIfNoHandlerFound设置为true
    2. P

      public class AppInitializer extends
              AbstractAnnotationConfigDispatcherServletInitializer {
      
        ....
        ......
      
        @Override
        protected FrameworkServlet createDispatcherServlet (WebApplicationContext wac) {
            DispatcherServlet ds = new DispatcherServlet(wac);
            //setting this flag to true will throw NoHandlerFoundException instead of 404 page
            ds.setThrowExceptionIfNoHandlerFound(true);
            return ds;
        }
      
      }
      

      请参阅完整示例here