1.在spring boot启动类里面添加这些代码:
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return (container -> {
ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error.html");
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/error.html");
ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error.html");
container.addErrorPages(error401Page, error404Page, error500Page);
});
}
2.定义error页面,要放到templates目录下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Error</title>
</head>
<body>
<div class="errorPage">
<span class="oops" th:text="#{oops}">Oops!</span><br/>
<p>
<span th:text="#{oops.message}">There seems to be a problem with the page you requested</span>
(<span th:text="${path}"></span>).
</p>
<p th:text="|#{oops.details}: ${message}|"></p>
</div>
</body>
</html>
具体error样式请根据自己的实际情况调整。
还可以根据不同的错误代码定义不同的error page.此处只用一个error page代替了。
------------------------
Spring Boot会为错误视图提供如下错误属性:
timestamp:错误发生的时间。
status:HTTP状态码。
error:错误原因。
exception:异常的类名。
message:异常消息(如果这个错误是由异常引起的)。
errors:BindingResult异常里的各种错误(如果这个错误是由异常引起的)。
trace:异常跟踪信息(如果这个错误是由异常引起的)。
path:错误发生时请求的URL路径。