2

Jetty 对我的应用程序帮助太大了。每当一些未处理的异常泄漏到顶部时,Jetty 就会自行构建一个非常冗长的响应并将其发送给我的客户

HTTP/1.1 500 com.mongodb.MongoException: No replica set members available in [ { address:'localhost/127.0.0.1:27017', ok:true, ping:0.49878865, isMaster:false, isSecondary:true, setName:dmReplSet, maxBsonObjectSize:16777216, },{ address:'localhost/127.0.0.1:27018', ok:true, ping:0.2565605, isMaster:false, isSecondary:true, setName:dmReplSet, maxBsonObjectSize:16777216, } ] for { "mode" : "primary"}

连同 14K 的 stacktrace 包裹在一个非常漂亮的 HTML 页面中。问题是,我不希望问题的细节泄露给客户,而且,这是一个 JSON Web App 接受和发出应用程序/json 内容,而不是 HTML Jetty 决定我的客户想要的。我想抑制这种默认错误处理,让 Jetty 只发出标准的 HTTP 500 响应

HTTP/1.1 500 Internal Server Error

而且根本没有身体。我该怎么做?似乎我应该能够告诉 Jetty 在 etc/jetty.xml 或 etc/jetty-webdefault.xml 或其他内容中“没有错误页面”。

4

1 回答 1

2

因此,这似乎最容易解决,而无需通过 web.xml 中的 <error-page> 将自己过多地绑定到 Jetty

<servlet>
    <servlet-name>ErrorHandler</servlet-name>
    <servlet-class>device.webapp.ErrorHandler</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>ErrorHandler</servlet-name>
    <url-pattern>/ErrorHandler</url-pattern>
</servlet-mapping>

<error-page>
    <exception-type>java.lang.Throwable</exception-type >
    <location>/ErrorHandler</location>
</error-page>

像这样实现 ErrorHandler

package device.webapp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.httpclient.*;
import org.slf4j.*;

/**
 * The ErrorHandler is intended to catch all unhandled Throwables (as configured in the web.xml)
 * before they get out to Jetty's verbose ErrorHandler.
 * 
 */
public class ErrorHandler extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private Logger log = LoggerFactory.getLogger( ErrorHandler.class );

    @Override
    protected void service( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException {
        // Analyze the servlet exception
        Throwable throwable = (Throwable) req.getAttribute( "javax.servlet.error.exception" );
        String message = String.format(
                "Responding 500 - Server Error on URI %s",
                req.getAttribute( "javax.servlet.error.request_uri" ) );
        if ( throwable != null ) {
            log.error( message, throwable );
        } else {
            log.warn( "Throwable should not be null!" );
            log.error( message );
        }

        /*
         * Interestingly enough, you can't resp.sendError( 500, "Server Error" ) without triggering
         * Jetty's DefaultErrorHandler which is the core of the problem we are trying to solve!
         */
        resp.setStatus( HttpStatus.SC_INTERNAL_SERVER_ERROR );
    }
}

它不漂亮,但它有效。

于 2013-08-09T20:35:52.557 回答