原理
一旦控制器中报出了异常,SpringBoot 会向/error的url发送请求。在SpringBoot中有一个叫BasicExceptionController的控制器来处理/error请求,然后跳转到默认显示异常的全局错误页面来展示异常信息。 如果没有使用ThymeLeaf模板,SpringBoot会到静态资源文件夹(META-INF/resources、resources、static、public)下寻找404.htm、500.html的错误提示页面,命名同上。使用ThymeLeaf模板时,SpringBoot会自动到src/main/resources/templates/error/文件夹下寻找404.htm、500.html的错误提示页面。 错误提示页面的命名规则是“错误代码.html”,比如404是404.html,500是500.html。错误代码的类型很多,如400、403、404等等,如果按照上面的方法,需要添加很多页面而SpringBoot提供了通用的命名方式,就是使用4xx.html、5xx.html命名,如:
- 4xx.html:表示能匹配到400、403、404……等错误
- 5xx.html:表示能匹配到500、501、502……等错误 如果404.html和4xx.html同时存在时,优先使用最匹配的,即当发生404错误时,优先匹配404.html页面。
@Controller
public class DispatcherController {
@GetMapping("/index")
public String index() throws IOException {
System.out.println(3/0);
return "index";
}
}
启动测试,假如:
- 请求路径为localhost/demo/index,则跳转到500页面
- 请求路径为localhost/demo/index324,则跳转到404页面 如果想让最终显示error页面,则需要自定义异常处理器:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ModelAndView exceptionHandler(HttpServletRequest req, Exception e) {
ModelAndView mav = new ModelAndView(); //此处不能将该变量直接定义在方法参数中
mav.addObject("url", req.getRequestURL());
mav.addObject("exception", e);
mav.setViewName("error/error");
return mav;
}
}