Jersey(1.19.1) - WebApplicationException and Mapping Exceptions to Responses

Previous sections have shown how to return HTTP responses and it is possible to return HTTP errors using the same mechanism. However, sometimes when programming in Java it is more natural to use exceptions for HTTP errors.

The following example shows the throwing of a NotFoundException from the bookmark sample:

@Path("items/{itemid}/")
public Item getItem(@PathParam("itemid") String itemid) {
    Item i = getItems().get(itemid);
    if (i == null) {
        throw new NotFoundException("Item, " + itemid + ", is not found");
    }
    return i;
}

This exception is a Jersey specific exception that extends WebApplicationException and builds a HTTP response with the 404 status code and an optional message as the body of the response:

public class NotFoundException extends WebApplicationException {
    /**
     * Create a HTTP 404 (Not Found) exception.
     */
    public NotFoundException() {
        super(Responses.notFound().build());
    }

    /**
     * Create a HTTP 404 (Not Found) exception.
     *
     * @param message
     *            the String that is the entity of the 404 response.
     */
    public NotFoundException(String message) {
        super(Response.status(Responses.NOT_FOUND).entity(message).type("text/plain").build());
    }
}

In other cases it may not be appropriate to throw instances of WebApplicationException, or classes that extend WebApplicationException, and instead it may be preferable to map an existing exception to a response. For such cases it is possible to use the ExceptionMapper<E extends Throwable> interface. For example, the following maps the EntityNotFoundException to a 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)
                .entity(ex.getMessage())
                .type("text/plain")
                .build();
    }
}

The above class is annotated with @Provider, this declares that the class is of interest to the JAX-RS runtime. Such a class may be added to the set of classes of the Application instance that is configured. When an application throws an EntityNotFoundException the toResponse method of the EntityNotFoundMapper instance will be invoked.

时间: 2024-10-08 00:29:31

Jersey(1.19.1) - WebApplicationException and Mapping Exceptions to Responses的相关文章

Jersey(1.19.1) - Hello World

1. Maven Dependency <properties> <jersey.version>1.19.1</jersey.version> </properties> <dependencies> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-core</artifactId> <versi

Jersey(1.19.1) - Hello World, Get started with Jersey using the embedded Grizzly server

Maven Dependencies The following Maven dependencies need to be added to the pom: <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.19.1</version> </dependency>

Jersey(1.19.1) - Conditional GETs and Returning 304 (Not Modified) Responses

Conditional GETs are a great way to reduce bandwidth, and potentially server-side performance, depending on how the information used to determine conditions is calculated. A well-designed web site may return 304 (Not Modified) responses for the many

Jersey(1.19.1) - Life-cycle of Root Resource Classes

By default the life-cycle of root resource classes is per-request, namely that a new instance of a root resource class is created every time the request URI path matches the root resource. This makes for a very natural programming model where constru

Jersey(1.19.1) - Deploying a RESTful Web Service

JAX-RS provides a deployment agnostic abstract class Application for declaring root resource and provider classes, and root resource and provider singleton instances. A Web service may extend this class to declare root resource and provider classes.

Jersey(1.19.1) - Client API, Proxy Configuration

为 Jersey Client 设置代理,可以使用带有 ClientHandler 参数的构造方法创建 Client 实例. public static void main(String[] args) { final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080)); Client client = new Client(new URLConnectionClientH

Jersey(1.19.1) - Security with Http(s)URLConnection

With Http(s)URLConnection The support for security, specifically HTTP authentication and/or cookie management with Http(s)URLConnection is limited due to constraints in the API. There are currently no specific features or properties on the Client cla

Jersey(1.19.1) - Using filters

Filtering requests and responses can provide useful functionality that is hidden from the application layer of building and sending requests, and processing responses. Filters can read/modify the request URI, headers and entity or read/modify the res

Jersey(1.19.1) - Extracting Request Parameters

Parameters of a resource method may be annotated with parameter-based annotations to extract information from a request. A previous example presented the use @PathParam to extract a path parameter from the path component of the request URL that match