【问题标题】:How to handle jersey and tomcat errors consistently?如何始终如一地处理球衣和 tomcat 错误?
【发布时间】:2014-12-13 03:45:22
【问题描述】:

我已经用球衣实现了一些(REST)服务。如果有错误的请求,球衣将处理错误并使用一些 JSON 内容进行回答。有一个 ExceptionMapper 应该可以捕获所有内容:

public class MyExceptionMapper implements ExceptionMapper<Throwable>

但是如果有一个无效的 HTTP 请求 - 例如无效的内容类型 - tomcat 在 jersey 有机会之前处理异常。生成的响应是一些丑陋的 tomcat HTML 错误页面,而不是所需的 JSON。

我知道可以在部署描述符中设置&lt;error-page&gt;,但我无法访问任何错误详细信息。

有没有办法防止tomcat捕获这个错误?如果是这样,jersey 可以使用其 ExceptionMapper 捕获它并返回正确的响应。

【问题讨论】:

    标签: java http tomcat error-handling jersey


    【解决方案1】:

    你知道你可以设置一个“错误页面”,但你指的是什么?如果它只是一个静态网页,那么是的,您将无法访问错误详细信息。但是如果你将它转发给一个用于处理错误的 servlet,那么你应该有关于你的错误的详细信息,并且可以将控制权交还给球衣等。

    web.xml:

      <error-page>
        <error-code>415</error-code>
        <location>/InvalidContentHandler</location>
      </error-page>
      <error-page>
        <exception-type>java.lang.Throwable</exception-type>
        <location>/InvalidContentHandler</location>
      </error-page>
    

    注意: 在上面的 web.xml 中,您应该将 java.lang.Throwable 替换为您遇到的实际异常类型,您可以使用“javax.servlet.error.exception " 属性,如下所示。

    InvalidContentHandler.java:

    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 {
    
        // Pass control to Jersey, or get some info:
        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");
        String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多