Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAX-RS: Convert Response to Exception

Tags:

java

rest

jax-rs

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)
}
like image 276
Xorty Avatar asked Apr 07 '14 09:04

Xorty


1 Answers

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.
like image 114
V G Avatar answered Sep 28 '22 03:09

V G