Dropwizard Response.status(Response.Status.NOT_FOUND).build() returns html

Viewed 465

In case of a genuine missing resource, my API returns the following

{
    "code": 404,
    "message": "HTTP 404 Not Found"
}

When I return a 404 through my resource using the code Response.status(Response.Status.NOT_FOUND).build() I get the following HTML as response

<html>

<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>Error 404 Not Found</title>
</head>

<body>
    <h2>HTTP ERROR 404 Not Found</h2>
    <table>
        <tr>
            <th>URI:</th>
            <td>/v1/2/1/100</td>
        </tr>
        <tr>
            <th>STATUS:</th>
            <td>404</td>
        </tr>
        <tr>
            <th>MESSAGE:</th>
            <td>Not Found</td>
        </tr>
        <tr>
            <th>SERVLET:</th>
            <td>io.dropwizard.jersey.setup.JerseyServletContainer-21c99abf</td>
        </tr>
    </table>

</body>

</html>

I am trying to figure out how I can block this unintended HTML and respond with no data.

2 Answers

We had the same issue and solved it by setting the .entity(...) to an empty String:

Response.status(NOT_FOUND).entity("").type(MediaType.APPLICATION_JSON).build()

Since that's kind of a hack, I am also eager to learn about cleaner solution(s) ... ;)

Set the Jersey property ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR to true.

environment.jersey()
        .property(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, true);

public static final String RESPONSE_SET_STATUS_OVER_SEND_ERROR

Whenever response status is 4xx or 5xx it is possible to choose between sendError or setStatus on container specific Response implementation. E.g. on servlet container Jersey can call HttpServletResponse.setStatus(...) or HttpServletResponse.sendError(...).

Calling sendError(...) method usually resets entity, response headers and provide error page for specified status code (e.g. servlet error-page configuration). However if you want to post-process response (e.g. by servlet filter) the only way to do it is calling setStatus(...) on container Response object.

If property value is true the method Response.setStatus(...) is used over default Response.sendError(...).

Type of the property value is boolean. The default value is false.

The name of the configuration property is "jersey.config.server.response.setStatusOverSendError".

Related