Xorty
Xorty

Reputation: 18851

JAX-RS: Convert Response to Exception

I am using JAX-RS client to consume REST API. I didn't want to let JAX-RS throw bunch of exceptions, so I am inspecting Response object myself. Sometimes however, I care only about certain status codes and I would like JAX-RS to fall back to default behavior and throw an actual exception (that will be handled by an AOP advice). Is there a simple way of doing this?

public void delete(long id) {
    Response response = client.delete(id);
    Response.Status status = Response.Status.fromStatusCode(response.getStatus());

    if (status == Response.Status.OK) {
        return;
    }
    if (status == Response.Status.NOT_FOUND) {
        throw new TeamNotFoundException();
    }
    if (status == Response.Status.CONFLICT) {
        throw new TeamHasAssignedUsersException();
    }

    // if status was internal server error or something similar, 
    // throw whatever exception you would throw at first place
    // magic.throwException(response)
}

Upvotes: 6

Views: 2128

Answers (1)

V G
V G

Reputation: 19002

There is no support in the JAX-RS API for translating a Response to an Exception. If you check the JerseyInvocation.convertToException() method, you will see that in Jersey it is a simple switch that translates the Response status to the corresponding Exception.

So, you have two options here:

  1. either you call webTarget.get(MyEntity.class) if you expect an entity body. Of course you can catch all WebApplicationException in a single catch clause, as all exceptions extend it (e.g check BadRequestException).
  2. or you make similar switch clause in your code, as jersey made.

Upvotes: 4

Related Questions