users@jersey.java.net

Re: [Jersey] Jersey client and exceptions

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Thu, 12 Feb 2009 10:17:56 +0100

On Feb 12, 2009, at 12:46 AM, Denis AH-KANG wrote:

> Hi all,
>
> I have some questions about the jersey client and its exceptions.
> Why does the client only throw runtime exceptions
> (ClientHandlerException and
> UniformInterfaceException)?
>


ClientHandlerException is thrown is there is an error reading/writing
the response e.g. an IOException.

UniformInterfaceException is thrown when status code of the HTTP
response indicates a response that is not expected. And in your
example below you need to refer to UniformInterfaceException.



> Actually, I need to use the client and manage the most common HTTP
> responses (400, 404, 500...).
> For the moment, I catch the client exception and get the status code
> from it. It means I need
> to create a switch case to handle each case. For instance:
>
> catch(ClientHandlerException e) {
> switch(e.getResponse().getResponseStatus()):
> case 400:
> //some code
> case 404:
> //some code
> ....
> }
>
> Do you know if there's a better way to use the jersey client?
>

The approach taken by the client API is by default to handle common
cases are not considered exceptional and uncommon cases like response
errors as exception cases.

So if i do a:

  String s = resource.get(String.class)

then a UniformInterfaceException will be thrown if the response has a
status code >= 300 and the response contains no entity.

If you do this:

  ClientResponse r = resource.get(ClientResponse.class);

then UniformInterfaceException will not be thrown. And it is up to you
to handle the response status in normal code blocks, for example:

    ClientResponse r = resource.get(ClientResponse.class);
    switch(r.getResponseStatus()):
         case 400:
             //some code
         case 404:
             //some code
         ....
    }

See the JavaDoc for more details:

   https://jersey.dev.java.net/source/browse/*checkout*/jersey/tags/jersey-1.0.1/api/jersey/com/sun/jersey/api/client/UniformInterface.html

Paul.