Spring Boot 2.7+ 浏览器请求没法匹配时404,500,自定义显示错误页面 Whitelabel Error Page This application has no explicit mapping for /error

发布时间 2023-09-08 11:45:16作者: tomcat and jerry

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri Sep 08 11:23:31 CST 2023
There was an unexpected error (type=Not Found, status=404).
 
浏览器直接请求,没有匹配的API时
会跳转到一个错误页面,显示不好看
 
如何自定义?
 
翻源码,有一个顶层接口:
/**
* Interface that can be implemented by beans that resolve error views.
*
* @author Phillip Webb
* @since 1.4.0
*/
@FunctionalInterface
public interface ErrorViewResolver {

/**
* Resolve an error view for the specified details.
* @param request the source request
* @param status the http status of the error
* @param model the suggested model to be used with the view
* @return a resolved {@link ModelAndView} or {@code null}
*/
ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model);

}


查看实现类
DefaultErrorViewResolver
当没有其他配置时,会走这个方法
private ModelAndView resolveResource(String viewName, Map<String, Object> model) {
for (String location : this.resources.getStaticLocations()) {
try {
Resource resource = this.applicationContext.getResource(location);
resource = resource.createRelative(viewName + ".html");
if (resource.exists()) {
return new ModelAndView(new HtmlResourceView(resource), model);
}
}
catch (Exception ex) {
}
}
return null;
}

实际会找/resources/META-INF/resources/error/ 这个目录下找有没有404.html 500/html
* 最终会编译到boot.jar: /META-INF/resources/error/

所以只要在这个目录下 加404.html 500.html即可