一,如果发生错误,
返回的页面内容如下
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Aug 04 16:02:48 CST 2016
There was an unexpected error (type=Internal Server Error, status=500).
二,在src/main/resources/templates下面新建error.html,则出现异常会跳转到error.html页面(我的spring boot采用了thymeleaf模板)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>error_test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h5>error page</h5>
</body>
</html>
但是以上的最终展示都对用户不够友好。
三,自定义异常处理
@ControllerAdvice
public class ExeptionHandler {
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) {
ModelAndView mv = new ModelAndView();
mv.addObject("e", e);
mv.addObject("uri", req.getRequestURI());
return mv;
}
}
然后修改error.html页面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>error_test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h5>error page</h5>
<div th:text="${uri}"></div>
<div th:text="${e.toString()}"></div>
</body>
</html>
测试示例:
try {
int a = 100/0;
} catch (Exception e) {
throw e;
}
页面最终显示
error page
/redis/get
java.lang.ArithmeticException: / by zero
四,tips:可以在application.properties里自定义错误页面的请求路径
比如
error.path=/error
具体springboot 异常处理的原理可以阅读 http://www.open-open.com/lib/view/open1446607376779.html