Springboot 统一异常处理

针对 404 其实 springmvc 提供了2种方式     404 是比较特殊的   

1.先设置dispatcherServlet

@Bean
public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
ServletRegistrationBean registration = new ServletRegistrationBean(
dispatcherServlet);
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
return registration;
}

2.再增加处理错误页面的handler,加上@ControllerAdvice 注解

@ControllerAdvice
public class GlobalControllerExceptionHandler {
public static final String DEFAULT_ERROR_VIEW = "pages/404";

@ExceptionHandler(value = NoHandlerFoundException.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", req.getRequestURL());
mav.setViewName(DEFAULT_ERROR_VIEW);
return mav;
}
}

针对上面这样的方法 存在一个弊端:会造成对js,css等资源的过滤,最好使用第二种方法

 

2. 集成ErrorController 

 

@Controller
public class MainsiteErrorController implements ErrorController {

private static final String ERROR_PATH = "/error";

@RequestMapping(value=ERROR_PATH)
public String handleError(){
return "pages/404";
}

@Override
public String getErrorPath() {
// TODO Auto-generated method stub
return ERROR_PATH;
}

}

推荐使用第二种

posted @ 2018-01-15 10:31  指针怒草内存栈  阅读(655)  评论(0编辑  收藏  举报