在web.xml中定义Exception和error-code的映射。
404
/404.html
0
/error.html
java.lang.NullPointerException
/error.html
HttpServletResponse.setError();
HttpServletResponse.sendError(status,msg);
请求处理流程

当异常发生时,首先在StandardHostValve 中匹配,匹配的规则是
找到对应的页面后,dispatch到相应的页面,返回给前端进行展示。
如果没有匹配到相应的页面,tomcat使用以下两种Value进行异常处理。
ErrorReportValve
用于在界面上展示错误信息,也就是常见的错误提示:

StandardWrapperValve
收集执行Servlet过程中的错误信息,给ErrorReportValve进行展示。

用于处理 HandlerMethod(上图中 Handler) 执行过程中抛出的异常
@Override
public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
ErrorPage errorPage = new ErrorPage(
this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));
errorPageRegistry.addErrorPages(errorPage);
}
by the way:code为0的错误页面映射,tomcat中的处理逻辑如下:
//org.apache.catalina.valves.ErrorReportValve
protected void report(Request request, Response response, Throwable throwable) {
int statusCode = response.getStatus();
// Do nothing on a 1xx, 2xx and 3xx status
// Do nothing if anything has been written already
// Do nothing if the response hasn't been explicitly marked as in error
// and that error has not been reported.
if (statusCode < 400 || response.getContentWritten() > 0 || !response.setErrorReported()) {
return;
}
// If an error has occurred that prevents further I/O, don't waste time
// producing an error report that will never be read
AtomicBoolean result = new AtomicBoolean(false);
response.getCoyoteResponse().action(ActionCode.IS_IO_ALLOWED, result);
if (!result.get()) {
return;
}
ErrorPage errorPage = null;
if (throwable != null) {
errorPage = errorPageSupport.find(throwable);
}
if (errorPage == null) {
errorPage = errorPageSupport.find(statusCode);
}
if (errorPage == null) {
// Default error page
errorPage = errorPageSupport.find(0);
}
... //忽略部分代码
}
返回给tomcat的ErrorReportValve去处理,展示异常如前图所示。