gpt4 book ai didi

java - Google App Engine Jersey 错误格式 json

转载 作者:行者123 更新时间:2023-12-01 09:49:39 26 4
gpt4 key购买 nike

我正在使用带有 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;
}

异常映射器:

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

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

最佳答案

您可以设置 Jersey 属性 ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERRORtrue

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

关于java - Google App Engine Jersey 错误格式 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37684055/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com