以通用方式处理它的唯一方法是使用如下所示的web.xml:
java.lang.Throwable
/ErrorHandler
servlet抛出ServletException和IOException,但是如果要在单个异常处理程序中处理运行时异常和所有其他异常,则可以将异常类型提供为Throwable.您可以使用多个错误页面条目来处理不同类型的异常并具有不同的处理程序.
例:
@WebServlet("/ErrorHandler")
public class ErrorHandler extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processError(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processError(request, response);
}
private void processError(HttpServletRequest request,
HttpServletResponse response) throws IOException {
//customize error message
Throwable throwable = (Throwable) request
.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
String servletName = (String) request
.getAttribute("javax.servlet.error.servlet_name");
if (servletName == null) {
servletName = "Unknown";
}
String requestUri = (String) request
.getAttribute("javax.servlet.error.request_uri");
if (requestUri == null) {
requestUri = "Unknown";
}
request.setAttribute("error", "Servlet " + servletName +
" has thrown an exception " + throwable.getClass().getName() +
" : " + throwable.getMessage());
request.getRequestDispatcher("/ErrorPage.jsp").forward(request, response);
}
}