users@jersey.java.net

[Jersey] Re: How to catch exceptions thrown when deserializing JSON

From: cowwoc <cowwoc_at_bbs.darktech.org>
Date: Wed, 03 Oct 2012 12:54:12 -0400

     This worked for me:

/**
  * @author Gili Tzabari
  */
@Provider
public class JsonProcessingExceptionMapper implements
ExceptionMapper<JsonProcessingException>
{
     private final com.google.inject.Provider<HttpRequestContext>
requestContext;

     /**
      * Creates a new JsonProcessingExceptionMapper.
      * <p/>
      * @param requestContext the entity associated with the request
      */
     @Inject
     public
JsonProcessingExceptionMapper(com.google.inject.Provider<HttpRequestContext>
requestContext)
     {
         this.requestContext = requestContext;
     }

     @Override
     public Response toResponse(JsonProcessingException e)
     {
         HttpRequestContext provider = requestContext.get();
         String entity = provider.getEntity(String.class);
         StringBuilder message;
         Throwable cause = e.getCause();
         if (cause instanceof EOFException)
             message = new StringBuilder("Entity may not be empty");
         else if (cause != null)
             message = new StringBuilder(cause.getMessage());
         else
         {
             message = new StringBuilder(e.getClass().getName()
                 + ": " + e.getMessage());
             if (e.getLocation() != null)
             {
                 int sourceStart = e.getMessage().indexOf("Source:");
                 int sourceEnd = e.getMessage().indexOf("line:",
sourceStart);
                 message.delete(sourceStart, sourceEnd);
             }
message.append("\nEntity:\n\"").append(entity).append("\"");
         }
         return
Response.status(Status.BAD_REQUEST).entity(message.toString()).type("text/plain").build();
     }
}

     You'll need to do the same for JsonMappingException.

Gili

On 03/10/2012 12:52 PM, jeff.sabin_at_gmail.com wrote:
> I have a resource that is using the Jackson deserialization to convert
> JSON to an object like this:
>
> @POST
> @Path ("/foobar")
> public Response add(Foo aFoo)
> {
> ....
> }
>
> If the JSON is not well formatted, I would like to catch and handle the
> exception that is thrown by Jackson. Is there a way to do this? I have
> tried using @Provider to catch Exception or Throwable or even the
> specific Jackson exceptions, but the provider is never called.
>
> Is there a way to do this, or do I have to deserialize by hand with in
> the resource method?
>
> Thanks for your help