在resources下的templates创建error文件夹,springboot错误时会自动来这里找文件,注:命名要规范,得是xxx.html(错误代码),也可以是自定义的(得配置),这里error.html是自定义的。
制造一个错误页面:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@GetMapping
public String index(){
int i = 9/0;
return "index";
}
}
接着是控制器:
Logger要用org.slf4j.Logger
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 //拦截所有有@Controller的控制器
public class ControllerExceptionHandler {
//拿到日志对象
private final Logger logger = LoggerFactory.getLogger(this.getClass());
// ModelAndView控制返回一个页面,加一些后台输出到前端的信息
@ExceptionHandler(Exception.class) //标识方法可以用来做异常处理,只要是Exception的都可以
public ModelAndView exceptionHander(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;
}
}
编辑前端的error.html页面:
前端用的thymeleaf
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<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>
th:each ==> for循环
th:utext ==> 对标签进行转义
th:remove ==>移除标签,使其在前端页面不显示,而查看网页源代码可以看到(注释)