invinc4u
invinc4u

Reputation: 1185

Dropwizard intercept bad json and return custom error message

I want to intercept a bad JSON input and return custom error messages using Dropwizard application. I followed the approach of defining a custom exception mapper as mentioned here : http://gary-rowe.com/agilestack/2012/10/23/how-to-implement-a-runtimeexceptionmapper-for-dropwizard/ . But it did not work for me. This same question has been asked here https://groups.google.com/forum/#!topic/dropwizard-user/r76Ny-pCveA but unanswered.

Any help would be highly appreciated.

My code below and I am registering it in dropwizard as environment.jersey().register(RuntimeExceptionMapper.class);

@Provider
public class RuntimeExceptionMapper implements ExceptionMapper<RuntimeException> {

    private static Logger logger = LoggerFactory.getLogger(RuntimeExceptionMapper.class);

    @Override
    public Response toResponse(RuntimeException runtime) {
        logger.error("API invocation failed. Runtime : {}, Message : {}", runtime, runtime.getMessage());
        return Response.serverError().type(MediaType.APPLICATION_JSON).entity(new Error()).build();
    }

}

Upvotes: 3

Views: 1670

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209004

Problem 1:

The exception being thrown by Jackson doesn't extends RuntimeException, but it does extend Exception. This doesn't matter though. (See Problem 2)

Problem 2:

DropwizardResourceConfig, registers it's own JsonProcessingExceptionMapper. So you should already see results similar to

{
    "message":"Unrecognized field \"field\" (class d.s.h.c.MyClass),..."
}

Now if you want to override this, then you should create a more specific exception mapper. When working with exception mappers the most specific one will be chosen. JsonProcessingException is subclassed by JsonMappingException and JsonProcessingException, so you will want to create an exception mapper for each of these. Then register them. I am not sure how to unregister the Dropwizard JsonProcessingExceptionMapper, otherwise we could just create a mapper for JsonProcessingException, which will save us the hassle of create both.

Update

So you can remove the Dropwizard mapper, if you want, with the following

Set<Object> providers = environment.jersey().getResourceConfig().getSingletons();
Iterator it = providers.iterator();
while (it.hasNext()) {
    Object val = it.next();
    if (val instanceof JsonProcessingExceptionMapper) {
        it.remove();
        break;
    }
}

Then you are free to use your own mapper, JsonProcessingException

Upvotes: 2

Related Questions