如何定义错误页面
404
500
error
在resources/error下建立自定义错误页面
- 如果有错误:
转到了我们自定义的错误页面:
自定义错误页面:
首先编写html页面
- 我们创建一个controller
@ControllerAdvice会拦截所有controller
@ExceptionHandler(Exception.class)回来处理某种类型的异常,这个例子里面处理的是exception错误
我们用ModelAndView来向前端传递数据,设置视图解析器,即访问路径,从而访问到我们的自定义错误html页面。
可以改进一波自定义的错误页面,在前端看到错误具体情况。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>error</title>
</head>
<body>
<h1>错误</h1>
<div>
<div th:utext="'<!--'" th:remove="tag"></div>
<div th:utext="'Failed Request URL : ' + ${url}" th:remove="tag"></div>
<div th:utext="'Exception message : ' + ${exception.message}" th:remove="tag"></div>
<ul th:remove="tag">
<li th:each="st : ${exception.stackTrace}" th:remove="tag"><span th:utext="${st}" th:remove="tag"></span></li>
</ul>
<div th:utext="'-->'" th:remove="tag"></div>
</div>
</body>
</html>
从而使我们可以通过查看源代码,在前端看到错误异常的具体情况,而不用去看后端日志:
自己定义异常
- 创建异常类,可以设置错误状态。