Vipul
Vipul

Reputation: 195

JAX RS Client: Catch exception message while making a REST call

I'm using ResteasyClient to make a REST client to my another service A. Say, service A throws an exception CustomException with a message : Got Invalid request. Here is how I am using the Client:

public Response callServiceA(final String query) {
    ResteasyClient client = new ResteasyClientBuilder().build();
    String link = "abc.com/serviceA";
    ResteasyWebTarget target = client.target(link).path("call");
    Form form = new Form();
    form.param("query", query);
    Response response;
    try {
        String data =
                target.request(MediaType.APPLICATION_JSON_TYPE)
                        .post(Entity.entity(form,
                                MediaType.APPLICATION_FORM_URLENCODED_TYPE),
                                String.class);
        response = Response.ok().entity(data).build();
    } catch (Exception e) {
        String message = e.getMessage();
        e.printStackTrace();
        response = Response.serverError().entity(e.getMessage()).build();
    } finally{
        client.close();
    }
    return response;
}

However, when I print the stacktrace, I'm unable to find my custom error message. I can just see the message as HTTP 400 Bad Request. Could you please suggest me how to access the error message?

NOTE: I am able to get the error message when I call the serviceA using the restClient. Hence, I dont think there is an issue with the service.

Upvotes: 1

Views: 2198

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208944

Don't deserialize the response straight to a String.

String data = ...
          .post(Entity.entity(form,
                MediaType.APPLICATION_FORM_URLENCODED_TYPE),
                String.class);

When you do this (and there is a problem), you just get a client side exception, which doesn't carry information about the response. Instead just get the Response with the overloaded post method

Response response = ...
          .post(Entity.entity(form,
                MediaType.APPLICATION_FORM_URLENCODED_TYPE));

Then you can get details from the Response, like the status and such. You can get the body with response.readEntity(String.class). This way you don't need to handle any exceptions. Just handle conditions based on the status.

Do note though that the Response above is an inbound Response, which is different from the outbound Response in your current code. So just make sure not to try and send out an inbound Response.

Also see this answer and it's comments for some design ideas.

Upvotes: 1

Related Questions