DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Breaking Up a Monolithic Database with Kong
  • Building REST API Backend Easily With Ballerina Language
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • Node.js REST API Frameworks

Trending

  • Getting Started With Agentic Workflows in Java and Quarkus
  • Every Cache Miss Is a Tiny Tax on Your Performance
  • The Missing `bandit` for AI Agents: How I Built a Static Analyzer for Prompt Injection
  • Building a Spring AI Assistant With MCP Servers: A Step-by-Step Tutorial
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Powerful Tactic to Use Exception Mapper in Dropwizard

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.

By 
Thamizh Arasu user avatar
Thamizh Arasu
·
May. 19, 16 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
20.9K Views

Join the DZone community and get the full member experience.

Join For Free
Dropwizard exception mapper

Problem

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:

  1. Introduce a custom exception
  2. Write an exception mapper for our newly introduced exception
  3. 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!       

REST API Web Protocols Error message code style Framework Web Service application career POST (HTTP) Infrastructure

Published at DZone with permission of Thamizh Arasu. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Breaking Up a Monolithic Database with Kong
  • Building REST API Backend Easily With Ballerina Language
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • Node.js REST API Frameworks

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook