Dropwizard : Exception Handling, giving custom error JSON error messages to client

Dheerendra picture Dheerendra · May 13, 2014 · Viewed 9k times · Source

How can i configure dropwizard to give custom error messages to User. If my function is supposed to return a object myObject, but since there is an error, it should throw and exception and return a error Object to User with a custom message.

Answer

condit picture condit · May 13, 2014

You can add your own subclass of WebApplicationException like this:

public class ObjectNotFoundException extends WebApplicationException {

  public ObjectNotFoundException() {
    super(Responses.notFound().build());
  }

  public ObjectNotFoundException(String message) {
    super(Response.status(Responses.NOT_FOUND).
    entity(message).type("text/plain").build());
  }

}

See the documentation for more information. You can also use ExceptionMappers if that makes more sense for your application.