Powerful Tactic to Use Exception Mapper in Dropwizard
When developing RESTful web services, people are often confused with handling exceptions. This post will explain a powerful tactic for using exception mapper with the Dropwizard framework.
Join the DZone community and get the full member experience.
Join For FreeProblem
When developing RESTful web services, people are often confused with handling exceptions. This post will explain a powerful tactic for using exception mapper with the Dropwizard framework. JAX-RS specification has already introduced exception mappers for handling such a situation in a great way. We will see how this problem was addressed in an effective way by using Dropwizard infrastructure.
How?
Now we will see how we can address this problem by checking out some real code with Dropwizard framework.
There are three steps involved for achieving this:
- Introduce a custom exception
- Write an exception mapper for our newly introduced exception
- Throw the custom exception from our REST API
Custom Exception
public class DropwizardSkolException extends Throwable {
private int code;
public DropwizardSkolException() {
this(500);
}
public DropwizardSkolException(int code) {
this(code, "Error while processing the request", null);
}
public DropwizardSkolException(int code, String message) {
this(code, message, null);
}
public DropwizardSkolException(int code, String message, Throwable throwable) {
super(message, throwable);
this.code = code;
}
public int getCode() {
return code;
}
}
Exception Mapper
@Provider
public class DropwizardSkolExceptionMapper implements ExceptionMapper<DropwizardSkolException> {
public Response toResponse(DropwizardSkolException exception) {
return Response.status(exception.getCode())
.entity(exception.getMessage())
.type(MediaType.TEXT_PLAIN)
.build();
}
}
REST API Changes
@DELETE
@Path("{isbn}")
public Response delete(@PathParam("isbn") String isbn) throws DropwizardSkolException {
logger.info("Enters delete()");
if (!"1416562605".equals(isbn)) {
final DropwizardSkolException exception = new DropwizardSkolException(404, "Book with mentioned isbn is NOT found");
throw exception;
}
return Response.ok("Book is deleted successfully").build();
}
Finally register the provider instance (Exception Mapper) into the Dropwizard application like below:
environment.jersey().register(new DropwizardSkolExceptionMapper());
Our job is done! You will see the proper error message as a response when you hit the API with an error scenario. I hope this article has helped you to understand how we can use custom exceptions with REST API.
Please share the article with your friends and provider your comments in the sidebar if any…
For a detailed code example refer https://github.com/cloudskol/dropwizardskol
Thank you!
Published at DZone with permission of Thamizh Arasu, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments