3

Typically one uses ExceptionMapper to catch exceptions, log them, return a customized error messages.

However while JAX-RS provides an NotFoundException in its api, the implementations (Jeresy, CXF,...) provide their own NotFoundException (such as com.sun.jersey.api.NotFoundException) which doesn't extends the JAX-RS one.

Leaving us with the sole option of having in our code implementation specific imports. This makes it hard if one wants to switch implementations.

Is there another way to do this, to avoid the dependency on a specific implementation?

Dudi
  • 2,340
  • 1
  • 24
  • 39

2 Answers2

1

"Is there another way to do this, to avoid the dependency on a specific implementation?"

Use a newer vendor version, that supports JAX-RS 2.0.

The WebApplicationException Hierarchy (i.e. javax.ws.rs.NotFoundException included) wasn't introduced until 2.0, though the WebApplicationException itself has existed since 1.0. That being said, below are the vendors and versions that started using JAX-RS 2.0

  • Resteasy 3.0.0
  • Jersey (RI) 2.0
  • CXF 2.7 (not full 2.0 - but close - full is in 3.0)

For prior releases, we could just use the WebApplicationException to wrap a response/status, like
throw new WebApplicationException(Response.Status.NOT_FOUND). You could then map this exception to the mapper, and getResponse().getStatus() from the exception if you needed to check the response status.

Any JAX-RS related exception, not thrown by us will also get wrapped in a WebApplicationException, so just having the mapper map to WebApplicationException should allow us to do what we need. A bit of a hassle to do all the checks.

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
1

A possible answer is to use javax.ws.rs.WebApplicationException

in your ExceptionMapper you can add

if (e instanceof WebApplicationException) // add this towards the end of the ExceptionMapper since it is a general exception
{
         // you can use the following for log or exception handling
        int status = ((WebApplicationException) e).getResponse().getStatus();
        if (status ==Response.Status.NOT_FOUND.getStatusCode())
        {
            //deal with 404
        }
        else
        {
          // deal with other http codes
        }

}
Dudi
  • 2,340
  • 1
  • 24
  • 39