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页面中。问题是,我不希望问题的细节泄露给客户,而且,这是一个接受和发送application/JSON内容的JSON Web应用程序,而不是HTML Jetty决定我的客户想要的。我想取消这种默认的错误处理,让Jetty只发出标准的HTTP500响应
HTTP/1.1 500 Internal Server Error
而且根本没有尸体。我该怎么做?我似乎可以告诉Jetty在etc/Jetty.xml或etc/Jetty-webdefault.xml或其他文件中"无错误页面"。
因此,这似乎最容易解决,而无需通过<错误页面>在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>
实现类似的错误处理程序
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 );
}
}
它不漂亮,但很管用。