2016-06-07 96 views
0

我正在用Jersey App和JAX-RS開發Google App Engine JAVA的REST API。 我希望能夠發送自定義錯誤給用戶JSON格式,我使用javax.ws.rs.ext.ExceptionMapperGoogle App Engine Jersey錯誤格式json

一切運作良好時,我在我的本地機器上運行與碼頭的應用程序,但是當我部署到谷歌,我得到默認的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頁面。

+0

您能指定/粘貼服務器錯誤堆棧嗎?你的代碼是否拋出NotFoundException? – Vijay

+0

那麼澤西捕獲NotFoundException並將其映射到HTTP 404響應。所以沒有堆棧 – Heigo

+0

我希望這個鏈接將幫助你http://stackoverflow.com/questions/26903729/how-to-handle-service-unavailable-scenarios-with-jersey-rest –

回答

1

您可以將澤西島物業ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR設置爲true

每當響應狀態爲4XX或者5XX有可能在容器具體實施ResponsesendError之間setStatus選擇。例如。在servlet容器澤西島上可以撥打HttpServletResponse.setStatus(...)HttpServletResponse.sendError(...)

調用sendError(...)方法通常會重置實體,響應標頭併爲指定的狀態代碼(例如servlet錯誤頁面配置)提供錯誤頁面。但是,如果要後處理響應(例如,通過servlet過濾器),唯一的方法是在容器響應對象上調用setStatus(...)

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

屬性值的類型是布爾值。 默認值爲假

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