- 编写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>error</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>
- 编写controller
package com.example.demo.handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
public class ControllerExceptionHandler {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@ExceptionHandler(Exception.class)
public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) {
logger.error("Request URL : {}, Exception : {}", request.getRequestURL(), e);
ModelAndView mv = new ModelAndView();
mv.addObject("url", request.getRequestURL());
mv.addObject("exception", e);
mv.setViewName("error/error");
return mv;
}
}
- 如果有错误发生:
可以发现错误
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/61c3cc44ba3ae3602f0bf2f6296cac29.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4c12902442d84142fe8abe6640811410.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/36d1dcd410198cda0c9a123d83e85669.png)