Reputation: 18851
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
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:
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).Upvotes: 4