簡體   English   中英

Google App Engine Jersey 錯誤格式 json

[英]Google App Engine Jersey error format 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;
}

異常映射器:

@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_ERROR設置為true

當響應狀態為 4xx 或 5xx 時,可以在容器特定的Response實現上在sendErrorsetStatus之間進行選擇。 例如,在 servlet 容器 Jersey 上可以調用HttpServletResponse.setStatus(...)HttpServletResponse.sendError(...)

調用sendError(...)方法通常會重置實體、響應頭並為指定的狀態代碼(例如 servlet 錯誤頁面配置)提供錯誤頁面 但是,如果您想對響應進行后處理(例如通過 servlet 過濾器),唯一的方法是在容器 Response 對象上調用setStatus(...)

如果屬性值為 true,則Response.setStatus(...)方法用於默認Response.sendError(...)

屬性值的類型是布爾值。 默認值為 false

配置屬性的名稱是"jersey.config.server.response.setStatusOverSendError"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM