咱们在作Web应用的时候,请求处理过程当中发生错误是很是常见的状况。Spring Boot提供了一个默认的映射:/error,当处理中抛出异常以后,会转到该请求中处理,而且该请求有一个全局的错误页面用来展现异常内容。 选择一个以前实现过的Web应用(Chapter3-1-2)为基础,启动该应用,访问一个不存在的URL,或是修改处理内容,直接抛出异常,如:html
@RequestMapping("/hello")
public String hello() throws Exception {
throw new Exception("发生错误");
}
复制代码
此时,能够看到相似下面的报错页面,该页面就是Spring Boot提供的默认error映射页面。bash
虽然,Spring Boot中实现了默认的error映射,可是在实际应用中,上面你的错误页面对用户来讲并不够友好,咱们一般须要去实现咱们本身的异常提示。函数
下面咱们以以前的Web应用例子为基础,进行统一异常处理的改造。ui
@ControllerAdvice
定义统一的异常处理类,而不是在每一个Controller中逐个定义。@ExceptionHandler
用来定义函数针对的异常类型,最后将Exception对象和请求URL映射到error.html
中@ControllerAdvice
class GlobalExceptionHandler {
public static final String DEFAULT_ERROR_VIEW = "error";
@ExceptionHandler(value = Exception.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;
}
}
复制代码
实现error.html
页面展现:在templates
目录下建立error.html
,将请求的URL和Exception对象的message输出。url
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>统一异常处理</title>
</head>
<body>
<h1>Error Handler</h1>
<div th:text="${url}"></div>
<div th:text="${exception.message}"></div>
</body>
</html>
复制代码
启动该应用,访问:http://localhost:8080/hello
,能够看到以下错误提示页面。spa
经过实现上述内容以后,咱们只须要在Controller
中抛出Exception
,固然咱们可能会有多种不一样的Exception
。而后在@ControllerAdvice
类中,根据抛出的具体Exception
类型匹配@ExceptionHandler
中配置的异常类型来匹配错误映射和处理。cdn
完整项目的源码来源 技术支持1791743380htm