users@jersey.java.net

Re: [Jersey] Re: Returning response in JSON format in case of Exceptions

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Mon, 10 May 2010 10:51:15 +0200

On May 5, 2010, at 10:28 PM, j2eeuser32 wrote:

>
> Paul,
>
> Thanks for your reply.
>
> After I posted, I realized I have to set an entity on the Response
> object
> which can be converted into JSON format. Thanks for confirming that.
>
> Here is a variant of the original problem:
>
> When I invoke a REST resource with a different Type of Path Param
> than what
> is expected, it throws a ParamException.
>
> I mapped the ParamException to an ExceptionMapper and set the
> FaultInfo
> Entity(which is annotated using @XMLRootElement) on it.
>
> In my client, irrespective of successful message or failure message, I
> always want to retrieve the Response as a String in JSON format like
> this:
>
>
> String responseString =
> resource.path("/test/
> dummy").accept(MediaType.APPLICATION_JSON_TYPE).get(String.class);
>

For any response >= 400 Jersey will throw a UniformInterfaceException
unless the type declared is ContainerResponse.class.



> But in case of this ParamException, I have to retrieve it like this:
>
> ClientResponse clientResponse =
> resource.path("/test/
> dummy
> ").accept(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
> out.println("REST response *** " +
> clientResponse.getEntity(String.class));
>
>
> What can be done to receive the response as a String?
>

The above will work irrespective of the status code and do what you
require.

Alternatively:

try {
   String response resource.path("/test/
dummy").accept(MediaType.APPLICATION_JSON_TYPE).get(String.class);
} catch (UniformInterfaceException ex) {
   // Check status
   if (ex.getResponse().getStatus() >= 400) {
     String getResponse()..getEntity(String.class);
   }
}

The important thing to do when writing the client is check the status
code. This is why the Jersey client attempts to enforce a certain way
of working as often clients should react differently for different
status codes.

Paul.