Jetty正在帮助我的应用程序太多。每当一些未处理的Exception漏掉顶部时,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内容的JSON Web应用程序,而不是HTML Jetty决定我的客户想要的。我想抑制Jetty只发出标准HTTP 500响应的默认错误处理
HTTP/1.1 500 Internal Server Error
根本没有身体。我怎么做到这一点?看起来我应该能够告诉Jetty在etc / jetty.xml或etc / jetty-webdefault.xml中的“无错误页面”等等。
答案 0 :(得分:2)
所以这似乎最容易解决,而不是通过< error-page>将自己绑定到Jetty上太多了。在web.xml中
<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>
像
一样实现ErrorHandlerpackage 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 );
}
}
它不漂亮,但它有效。