Dropwizard Handle Exceptions

I’ve made a sample application showing how to create an exception provider which catches exceptions thrown inside resources and handles them gracefully in your application.

This example uses a Jetty Provider ExceptionMapper (RuntimeExceptionMapper.java) to handle any RuntimeExceptions thrown inside the application, which logs the exception and returns an appropriate response.

package com.example.providers;

...
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
...

@Provider
public class RuntimeExceptionMapper implements ExceptionMapper<RuntimeException> {

    @Override
    public Response toResponse(RuntimeException exception) {

        Response response500 = Response
                .serverError()
                .entity(new ErrorView(exception, "500.ftl"))
                .build();

        ...

        return response500;
    }
}

The provider should be added to the environment in the Run method of the Service class.

package com.example;

...

public class ExampleService extends com.yammer.dropwizard.Service<ExampleConfiguration> {

    public static void main(String[] args) throws Exception
    {
        new com.example.ExampleService().run(args);
    }

    @Override
    public void initialize(Bootstrap bootstrap) {
        bootstrap.setName("dropwizard-handle-exceptions");
        bootstrap.addBundle(new ViewBundle());
    }

    @Override
    public void run(ExampleConfiguration configuration, Environment environment) throws Exception {
        environment.addResource(new UserResource());

        environment.addProvider(new RuntimeExceptionMapper());
    }
}

Got the idea from here.

Advertisements

3 thoughts on “Dropwizard Handle Exceptions

  1. Hi Steven, as usual, excellent post.
    I used your classes but for some reason when i have JDBC or Database exceptions, it is always returning 500. Anyway to show the exact problem, like duplicate entries, nulls, etc.?
    Thank you so much.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s