Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are several approaches to customize the error handling behavior with JAX-RS. Here are three of the easier ways.</p> <p>The first approach is to create an Exception class that extends WebApplicationException.</p> <p>Example:</p> <pre><code>public class NotAuthorizedException extends WebApplicationException { public NotAuthorizedException(String message) { super(Response.status(Response.Status.UNAUTHORIZED) .entity(message).type(MediaType.TEXT_PLAIN).build()); } } </code></pre> <p>And to throw this newly create Exception you simply:</p> <pre><code>@Path("accounts/{accountId}/") public Item getItem(@PathParam("accountId") String accountId) { // An unauthorized user tries to enter throw new NotAuthorizedException("You Don't Have Permission"); } </code></pre> <p>Notice, you don't need to declare the exception in a throws clause because WebApplicationException is a runtime Exception. This will return a 401 response to the client.</p> <p>The second and easier approach is to simply construct an instance of the WebApplicationException directly in your code. This approach works as long as you don't have to implement your own application Exceptions. </p> <p>Example:</p> <pre><code>@Path("accounts/{accountId}/") public Item getItem(@PathParam("accountId") String accountId) { // An unauthorized user tries to enter throw new WebApplicationException(Response.Status.UNAUTHORIZED); } </code></pre> <p>This code too returns a 401 to the client.</p> <p>Of course, this is just a simple example. You can make the Exception much more complex if necessary, and you can generate what ever http response code you need to. </p> <p>One other approach is to wrap an existing Exception, perhaps an ObjectNotFoundException with an small wrapper class that implements the ExceptionMapper interface annotated with a @Provider annotation. This tells the JAX-RS runtime, that if the wrapped Exception is raised, return the response code defined in the ExceptionMapper. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload