user1183772
user1183772

Reputation:

Disable default error response body in Jetty 9.4.2

How can I disable the default response body when Jetty catches an exception and returns an error? I am not using any XML or WAR and I don't want to add any.

I prefer to avoid doing a try { // Servlet code } catch (Exception e) { resp.setStatus(500) } in every servlet.

If I don't do that, Jetty will return a 500 response with a body that specifies the stack trace. If a not found endpoint is reached, Jetty will return a 404 response with a body that says "Powered by Jetty". I want to remove those bodies and just keep the response code.

This is the code that starts my Jetty server:

private static void startServer() throws Exception {
    final org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(7070);
    final WebAppContext context = new WebAppContext("/", "/");
    context.setConfigurations(new Configuration[] { new AnnotationConfiguration(), new WebInfConfiguration() });
    context.setExtraClasspath("build/classes/main/com/example");
    server.setHandler(context);
    server.start();
    server.join();
}

Upvotes: 3

Views: 6589

Answers (2)

user1183772
user1183772

Reputation:

The solution is described in the Jetty documentation:

A class extending ErrorHandler is needed in order to override Jetty default behavior when generating the error page. It may be registered via the ContextHandler or the Jetty server.

The CustomErrorHandler class:

public class CustomErrorHandler extends ErrorHandler {

    @Override
    protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks) throws IOException {}
}

I then added this to my Jetty embedded configuration: context.setErrorHandler(new CustomErrorHandler());

Upvotes: 3

Joakim Erdfelt
Joakim Erdfelt

Reputation: 49555

In your WEB-INF/web.xml of your war file, specify the <error-page> element you want to use to handle the errors.

Example:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
  <servlet>
    <servlet-name>myerror</servlet-name>
    <servlet-class>com.company.MyErrorServlet</servlet-class>
  </servlet>

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

  <error-page>
    <location>/myerror</location>
  </error-page>
</web-app>

The <error-page> element can be quite powerful.

See other answer at https://stackoverflow.com/a/16340504/775715

Upvotes: 1

Related Questions