Search code examples
javagoogle-app-engineexceptionjerseyjax-rs

Google App Engine Jersey error format json


I'm developing a REST API with Google App Engine JAVA with Jersey and JAX-RS. I want to be able to send custom errors to users in JSON format, for that I'm using javax.ws.rs.ext.ExceptionMapper

All works well when I run the app with Jetty on my local machine, but when I deploy to Google I get the default HTML 404 page

Here is the resource code:

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
public Customer getCustomer(@PathParam("id") String id) {
    Customer customer = getCustomer(id);
    if(customer == null)
        throw new NotFoundException("Customer not found");
    return customer;
}

The exception mapper:

@Provider
public class NotFoundExceptionMapper implements ExceptionMapper<NotFoundException> {

@Override
public Response toResponse(NotFoundException e) {
    ErrorMessage errorMessage = new ErrorMessage();
    errorMessage.setErrrorMessage(e.getMessage());
    errorMessage.setResponseCode(404);
    return Response.status(Response.Status.NOT_FOUND).entity(errorMessage).type(MediaType.APPLICATION_JSON_TYPE).build();
}    
}

I expect to get the JSON formatted ErrorMessage object as response, but all I get is the default HTML 404 page.


Solution

  • You can set the Jersey property ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR to true.

    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".