How to catch 404 (NotFoundException) without being dependent on JAX-RS implementation?

Typically, ExceptionMapper used to catch exceptions, log them, and return customized error messages.

However, although JAX-RS provides a NotFoundException in its api, implementations (Jeresy, CXF, ...) provide their own NotFoundException (e.g. com.sun.jersey.api.NotFoundException ), which does not extend JAX-RS.

Leaving us with the only option of having code implementation in our concrete implementation. This makes the task harder if you want to switch implementations.

Is there any other way to do this in order to avoid dependency on a particular implementation?

+2
source share
2 answers

"Is there any other way to do this to avoid being dependent on a particular implementation?"

Use the new vendor version that supports JAX-RS 2.0.

The WebApplicationException hierarchy (i.e. javax.ws.rs.NotFoundException included) was not introduced before 2.0, but WebApplicationException itself existed from 1.0. 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 previous releases, we could just use WebApplicationException to wrap the response / status, e.g.
throw new WebApplicationException(Response.Status.NOT_FOUND) . You can then map this exception to the mapper and getResponse().getStatus() from the exception if you need to check the status of the response.

Any JAX-RS related exception that we don’t WebApplicationException will also be wrapped in a WebApplicationException , so just displaying the WebApplicationException map should allow us to do what we need. A bit of a hassle to do all the checks.

+1
source

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

in 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 } } 
+1
source

Source: https://habr.com/ru/post/978024/


All Articles