Previous sections has shown how to return HTTP responses and it's possible to return HTTP errors using the same Mechanis M. However, sometimes when programming in Java it was more natural the use of exceptions for HTTP errors.
The following example shows the throwing of a from the NotFoundException bookmark sample:
@Path ("items/{itemid}/") public Item GetItem (@PathParam ("itemid") String itemid) { = GetItems (). get (itemid); if NULL {thrownew notfoundexception ("Item," + Itemid + ", is not Found"); } return i;}
This exception was a Jersey specific exception that extends webapplicationexception and builds a HTTP response W ith the 404 status Code and an optional message as the body of the response:
Public classNotfoundexceptionextendswebapplicationexception {/*** Create a HTTP 404 (not Found) exception. */ Publicnotfoundexception () {Super(Responses.notfound (). build ()); } /*** Create a HTTP 404 (not Found) exception. * * @paramMessage * The String that is the entity of the 404 response. */ Publicnotfoundexception (String message) {Super(Response.Status (Responses.not_found). Entity (Message). Type ("Text/plain"). Build ()); }}
In the other cases it is appropriate to throw the instances of webapplicationexception, or classes that extend Webapplicat Ionexception, and instead it may is preferable to map the existing exception to a response. For such cases it was possible to use the Exceptionmapper<e extends Throwable> interface. For example, the following maps the entitynotfoundexception to an HTTP 404 (not Found) response:
@Provider public class entitynotfoundmapper implements exceptionmapper< Javax.persistence.entitynotfoundexception> { public Response Toresponse (Javax.persistence.EntityNotFoundException ex) { return response.status (404 "Text/plain"
The above class is annotated with @Provider, this declares, the class is of the interest to the JAX-RS runtime. Such A class may, added to the set of classes of the application instance, is configured. When a application throws an Entitynotfoundexception the method of the instance would be toResponse EntityNotFoundMapper invoked.
Jersey (1.19.1)-webapplicationexception and Mapping Exceptions to responses