Search

Chapter 24. Exception Handling

download PDF

24.1. Exception Mappers

ExceptionMappers are custom, application-provided components that can catch application exceptions and write specific HTTP responses. They are associated with @Provider, and implement the following interface:
         package javax.ws.rs.ext;

         import javax.ws.rs.core.Response;

         /**
         * Contract for a provider that maps Java exceptions to
         * {@link javax.ws.rs.core.Response}. An implementation of this interface must
         * be annotated with {@link Provider}.
         *
         * @see Provider
         * @see javax.ws.rs.core.Response
         */
         public interface ExceptionMapper<E>
         {

         /**
         * Map an exception to a {@link javax.ws.rs.core.Response}.
         *
         * @param exception the exception to map to a response
         * @return a response mapped from the supplied exception
         */
         Response toResponse(E exception);
         }
When an application throws an exception, the exception is caught by the JAX-RS runtime. JAX-RS then scans registered ExceptionMappers to locate one which supports marshalling the exception type thrown. An example ExceptionMapper follows:

         @Provider
         public class EJBExceptionMapper implements ExceptionMapper<javax.ejb.EJBException>
         {

         Response toResponse(EJBException exception) {
         return Response.status(500).build();
         }

         }
ExceptionMappers are registered in the same way as MessageBodyReaders and MessageBodyWriters: by scanning through the RESTEasy provider context-param (if you are deploying in a WAR file), or programmatically through the ResteasyProviderFactory class.
Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.