Jakarta EE Servlet Exception Handling – Jakarta EE的Servlet异常处理

最后修改: 2018年 6月 20日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this tutorial, we’re going to handle exceptions in a Jakarta EE Servlet application – in order to provide a graceful and expected outcome whenever an error happens.

在本教程中,我们将在Jakarta EE Servlet应用程序中处理异常–以便在发生错误时提供一个优雅的预期结果。

2. Jakarta EE Servlet Exceptions

2.雅加达EE的Servlet异常

First, we’ll define a Servlet using the API annotations (have a look at the Servlets Intro for more details) with a default GET processor that will throw an exception:

首先,我们将使用API注解来定义一个Servlet(请看Servlets介绍以了解更多细节),它有一个默认的GET处理器,将抛出一个例外。

@WebServlet(urlPatterns = "/randomError")
public class RandomErrorServlet extends HttpServlet {

    @Override
    protected void doGet(
      HttpServletRequest req, 
      HttpServletResponse resp) {
        throw new IllegalStateException("Random error");
    }
}

3. Default Error Handling

默认的错误处理

Let’s now simply deploy the application into our servlet container (we’re going to assume that the application runs under http://localhost:8080/javax-servlets).

现在让我们简单地将应用程序部署到我们的servlet容器中(我们将假设该应用程序运行在http://localhost:8080/javax-servlets)。

When we access the address http://localhost:8080/javax-servlets/randomError, we’ll see the default servlet error handling in place:

当我们访问地址http://localhost:8080/javax-servlets/randomError时,我们将看到默认的Servlet错误处理。

servlet

servlet

Default error handling is provided by the servlet container and can be customized at a container or application level.

默认的错误处理是由servlet容器提供的,可以在容器或应用程序级别上进行自定义。

4. Custom Error Handling

4.自定义错误处理

We can define custom error handling using a web.xml file descriptor in which we can define the following types of policies:

我们可以使用web.xml文件描述符来定义自定义错误处理,在其中我们可以定义以下类型的策略。

  • Status code error handling – it allows us to map HTTP error codes (client and server) to a static HTML error page or an error handling servlet
  • Exception type error handling – it allows us to map exception types to static HTML error pages or an error handling servlet

4.1. Status Code Error Handling with an HTML Page

4.1.用HTML页面处理状态代码错误

We can set up our custom error handling policy for HTTP 404 errors in the web.xml:

我们可以在web.xml中为HTTP 404错误设置我们的自定义错误处理策略。

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns="http://java.sun.com/xml/ns/javaee"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1">

    <error-page>
        <error-code>404</error-code>
        <location>/error-404.html</location> <!-- /src/main/webapp/error-404.html-->
    </error-page>

</web-app>

Now, access http://localhost:8080/javax-servlets/invalid.html from the browser – to get the static HTML error page.

现在,从浏览器访问http://localhost:8080/javax-servlets/invalid.html–以获得静态HTML错误页面。

4.2. Exception Type Error Handling with a Servlet

4.2.用Servlet处理异常类型的错误

We can set up our custom error handling policy for java.lang.Exception in web.xml:

我们可以在web.xml中为java.lang.Exception设置我们自定义的错误处理策略。

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns="http://java.sun.com/xml/ns/javaee"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1">
    <error-page> 
        <exception-type>java.lang.Exception</exception-type> 
        <location>/errorHandler</location> 
    </error-page>
</web-app>

In ErrorHandlerServlet, we can access the error details using the error attributes provided in the request:

ErrorHandlerServlet中,我们可以使用请求中提供的错误属性来访问错误细节。

@WebServlet(urlPatterns = "/errorHandler")
public class ErrorHandlerServlet extends HttpServlet {

    @Override
    protected void doGet(
      HttpServletRequest req, 
      HttpServletResponse resp) throws IOException {
 
        resp.setContentType("text/html; charset=utf-8");
        try (PrintWriter writer = resp.getWriter()) {
            writer.write("<html><head><title>Error description</title></head><body>");
            writer.write("<h2>Error description</h2>");
            writer.write("<ul>");
            Arrays.asList(
              ERROR_STATUS_CODE, 
              ERROR_EXCEPTION_TYPE, 
              ERROR_MESSAGE)
              .forEach(e ->
                writer.write("<li>" + e + ":" + req.getAttribute(e) + " </li>")
            );
            writer.write("</ul>");
            writer.write("</html></body>");
        }
    }
}

Now, we can access http://localhost:8080/javax-servlets/randomError to see the custom error servlet working.

现在,我们可以访问http://localhost:8080/javax-servlets/randomError,以看到自定义错误Servlet的工作。

Note: Our exception type defined in the web.xml is too broad and we should specify all the exceptions we want to handle in more detail.

注意。我们在web.xml中定义的异常类型过于宽泛,我们应该更详细地指定我们想要处理的所有异常。

We can also use the container-provided servlet logger in our ErrorHandlerServlet component to log additional details:

我们还可以在我们的ErrorHandlerServlet组件中使用容器提供的servlet记录器来记录额外的细节。

Exception exception = (Exception) req.getAttribute(ERROR_EXCEPTION);
if (IllegalArgumentException.class.isInstance(exception)) {
    getServletContext()
      .log("Error on an application argument", exception);
}

It’s worth knowing what’s beyond the servlet-provided logging mechanisms, check the guide on slf4j for more details.

值得了解的是,在servlet提供的日志机制之外还有什么,请查看关于slf4j的指南以了解更多细节。

5. Conclusion

5.总结

In this brief article, we have seen default error handling and specified custom error handling in a servlet application without adding external components nor libraries.

在这篇简短的文章中,我们已经看到了默认的错误处理和在一个servlet应用程序中指定的自定义错误处理,而无需添加外部组件或库。

As always, you can find the source code over on Servlets tutorial repository.

一如既往,你可以在Servlets教程库上找到源代码。