springmvc返回Whitelabel Error Page是因为
1、请求路径不对;
2、返回的视图对象无法解析
当找不到对应资源的时候,TemplateManager无法解析视图名时,会抛出异常Error resolving template [index1], template might not exist or might not be accessible by any of the configured Template Resolvers,Tomcat会捕获异常,然后发起一个
/demo/error的请求,这个请求会转发到一个BasicErrorController空控制器,该控制器 会返回一个ErrorMvcAutoConfiguration#StaticView,
@Override
public void render(Map<String, ?> model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
if (response.isCommitted()) {
String message = getMessage(model);
logger.error(message);
return;
}
StringBuilder builder = new StringBuilder();
Date timestamp = (Date) model.get("timestamp");
Object message = model.get("message");
Object trace = model.get("trace");
if (response.getContentType() == null) {
response.setContentType(getContentType());
}
builder.append("<html><body><h1>Whitelabel Error Page</h1>").append(
"<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>")
.append("<div id='created'>").append(timestamp).append("</div>")
.append("<div>There was an unexpected error (type=")
.append(htmlEscape(model.get("error"))).append(", status=")
.append(htmlEscape(model.get("status"))).append(").</div>");
if (message != null) {
builder.append("<div>").append(htmlEscape(message)).append("</div>");
}
if (trace != null) {
builder.append("<div>").append(htmlEscape(trace)).append("</div>");
}
builder.append("</body></html>");
response.getWriter().append(builder.toString());
}
ErrorController接口可以处理所有的异常,包括未进入控制器(controller)之前的异常
而注解@ControllerAdvice方式只能处理控制器抛出的异常。此时请求已经进入控制器中。因此无法拦截404、401等错误。
如果ErrorController和@ControllerAdvice同时存在,那么@ControllerAdvice优先处理,@ControllerAdvice处理不了的才会到ErrorController处理。