Custom Jersey Error Handling, how to catch response at client side?

冷暖自知 提交于 2019-12-05 19:17:54

Is there a way to get the errorMessage on the client side (in the catch block) without using Response as a return type?

You can use response.readEntity(new GenericType<List<Country>>(){}). This way you will still have access to the Response. Though in this case there will be no stacktrace. There is only an exception on the client when you try to use get(ParsedType). The reason is that with get(ParsedType), there is no other way to handle the error status. But using Response, the developer should do the checking against the status. So the method could look more like

public List<Country> findAll() throws ClientErrorException {
    WebTarget resource = webTarget;
    resource = resource.path("countries");
    Response response =  resource.request(javax.ws.rs.core.MediaType.APPLICATION_XML).get();
    if (response.getStatus() != 200) {
        System.out.println(response.getHeaderString("errorResponse"));
        return null;
    } else {
        return response.readEntity(new GenericType<List<Country>>(){});
    }
}

Though instead of in the header, I would just send the message out as the response body. That's just me

super(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
        .entity( message).type(MediaType.TEXT_PLAIN).build());

Client side

if (response.getStatus() != 200) {
    System.out.println(response.readEntity(String.class));
    return null;
}
jas_raj

I don't believe that you can return custom content (i.e. errorMessage) in any response type except HTTP 200 (Response.ok().build).

However, you can throw exceptions within your server code and then catch them and convert them to valid responses with an ExceptionMapper. See this question for more details.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!