How to catch 404 (NotFoundException) without being depndant on a JAX-RS implemenation?

喜夏-厌秋 提交于 2019-12-10 21:43:58

问题


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?


回答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.




回答2:


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
        }

}


来源:https://stackoverflow.com/questions/26914088/how-to-catch-404-notfoundexception-without-being-depndant-on-a-jax-rs-implemen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!