Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

Handling Exception Scenarios in REST API developed using JAX-RS

October 2, 2017
Rahul Kumar
Related topics:
JavaMicroservices
Related products:
Red Hat Enterprise Linux

    Prerequisite: Hands on Knowledge of REST API Development using JAX-RS.

    REST Services has been an integral part of complex enterprise applications for several years. Developers generally prefer two APIs listed below for building REST API in their enterprise applications.

    1. JAX-RS – Part of JEE Specification with different implementations like RestEasy, Jersey, Restlet etc.
    2. Spring Boot – An OpenSource Spring Community Project best suited for Microservices-based applications.

    In this Article, we will learn how to handle Exceptions gracefully in Rest APIs which are built using JAX-RS.

    Example

    Lets take an example of an Social Media application like Twitter, deployed in some Application/Web server like Tomcat. A sample REST Endpoint in Twitter API could be like so:

    /tweet/{tweetID}
    // Gives Client a particular tweet based on tweet ID provided.

    Now what if the Client sends a tweetID for which there is no tweet available in database. For example:

    /tweet/25
    // no content(as Response)

    It's not something that the Client of the Rest Service wants to see. In such cases, we can create our own custom exceptions. This way, if someone tries to access a tweet that's not available in server, we simply throw an exception rather return empty content.

    STEP 1: Create Custom Exception

    public class INFONotFoundException extends RuntimeException {
        private static final long serialVersionUID = 1L;
    
        public INFONotFoundException(String message) {
            super(message);
        }
    }

    Now if we access /tweet/25 but the particular tweet ID isn't available, we get the Tomcat Error Page because we are throwing INFONotFoundException in our business class but not catching it. It bubbles up in JAX_RS, which also doesn't know what to do with this exception, so it goes up to servlet container which has a default behavior to show standard error page in case something wrong happened in server side code.

    We don't want an HTML error Page for the exception as the response of Rest API End Point, though. We want a JSON payload as the response so it is useful to the client who is consuming the REST API, so they can parse it accordingly. For this, we would like JAX-RS framework to catch it and return a JSON payload before it goes up to servlet container.

    STEP 2:  Map Custom Exception to JSON Payload(e.g ErrorResponse) using JAX-RS ExceptionMapper

    public class ErrorResponse {
      String errorMessage;
      String errorCode;
      String documentationLink;
      
      public ErrorResponse(String errorMessage, String errorCode, String documentationLink) {
        super();
        this.errorMessage = errorMessage;
        this.errorCode = errorCode;
        this.documentationLink = documentationLink;
      }
      
      public ErrorResponse() {
      
      }
      // Getters and Setters
    }
    @Provider
    public class INFONotFoundExceptionMapper implements ExceptionMapper<INFONotFoundException> {
      @Override
      public Response toResponse(INFONotFoundException ex) {
        ErrorResponse response = new ErrorResponse(ex.getMessage(), "503",
          "https://docs.oracle.com/javaee/7/api/javax/ws/rs/ext/ExceptionMapper.html");
        return Response.ok().entity(response).build();
      }
    }

    Now, when JAX-RS sees any INFONotFoundException in the application, it searches all ExceptionMapper's annotated with @Provider in application and tries to find a mapper which could map the INFONotFoundException to a ErrorResponse. Once it finds a suitable ExceptionMapper, it passes the thrown Exception to the method argument of toResponse(Exception ex) in ExceptionMapper and builds a JSON payload by calling toResponse(Exception e) method of ExceptionMapper.

    Now, the client does not see an HTML error page anymore and JAX-RS gives a nice JSON payload which can help the client with troubleshooting.

    Note:

    1. We can include ExceptionMapper in our REST API in order to address specific Exceptions to be more helpful to the client.

    2. It's always good practice to create a generic ExceptionMapper in case the developer doesn't want to create multiple mappers for each exception thrown in application. This way, no matter what goes wrong in our server side REST API (e.g NullPointerException, DataNotFoundException, etc.), JAX-RS always tries to map it with GenericExceptionMapper and we never see the HTML Error page but instead a JSON payload which can be helpful for the service client.

    @Provider
    public class GenericExceptionMapper implements ExceptionMapper<Throwable> {
      
      @Override
      public Response toResponse(Throwable arg0) {
        // TODO Auto-generated method stub
        return null;
      }
    }
    Last updated: June 8, 2021

    Recent Posts

    • SQL Server HA on RHEL: Meet Pacemaker HA Agent v2 (tech preview)

    • Deploy with confidence: Continuous integration and continuous delivery for agentic AI

    • Every layer counts: Defense in depth for AI agents with Red Hat AI

    • Fun in the RUN instruction: Why container builds with distroless images can surprise you

    • Trusted software factory: Building trust in the agentic AI era

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Chat Support

    Please log in with your Red Hat account to access chat support.