Google App Engine Jersey错误格式json

我正在使用带有Jersey和JAX-RS的Google App Engine JAVA开发REST API。 我希望能够以JSON格式向用户发送自定义错误,因为我正在使用javax.ws.rs.ext.ExceptionMapper

当我在本地计算机上使用Jetty运行应用程序时,一切正常,但是当我部署到Google时,我得到了默认的HTML 404页面

这是资源代码:

 @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; } 

exception映射器:

 @Provider public class NotFoundExceptionMapper implements ExceptionMapper { @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(); } } 

我希望得到JSON格式的ErrorMessage对象作为响应,但我得到的只是默认的HTML 404页面。

您可以将Jersey属性ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR设置为true

每当响应状态为4xx或5xx时,可以在容器特定的Response实现上选择sendErrorsetStatus 。 例如,在servlet容器上,Jersey可以调用HttpServletResponse.setStatus(...)HttpServletResponse.sendError(...)

调用sendError(...)方法通常会重置实体,响应头并为指定的状态代码提供错误页面 (例如,servlet错误页面配置)。 但是,如果要进行后处理响应(例如,通过servletfilter),唯一的方法是在容器Response对象上调用setStatus(...)

如果属性值为true,则使用方法Response.setStatus(...)而不是默认的Response.sendError(...)

属性值的类型是boolean。 默认值为false

配置属性的名称是"jersey.config.server.response.setStatusOverSendError"