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.

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

  1. Jersey(1.19.1) - Hello World, Get started with a Web application

    1. Maven Dependency <properties> <jersey.version>1.19.1</jersey.version> </prop ...

  2. Jersey(1.19.1) - JSON Support

    Jersey JSON support comes as a set of JAX-RS MessageBodyReader<T> and MessageBodyWriter<T&g ...

  3. 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> ...

  4. Jersey(1.19.1) - Root Resource Classes

    Root resource classes are POJOs (Plain Old Java Objects) that are annotated with @Path have at least ...

  5. Jersey(1.19.1) - Deploying a RESTful Web Service

    JAX-RS provides a deployment agnostic abstract class Application for declaring root resource and pro ...

  6. Jersey(1.19.1) - Extracting Request Parameters

    Parameters of a resource method may be annotated with parameter-based annotations to extract informa ...

  7. Jersey(1.19.1) - Representations and Java Types

    Previous sections on @Produces and @Consumes referred to MIME media types of representations and sho ...

  8. 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, depen ...

  9. 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 r ...

随机推荐

  1. HDU 3308 LCIS (线段树区间合并)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3308 题目很好懂,就是单点更新,然后求区间的最长上升子序列. 线段树区间合并问题,注意合并的条件是a[ ...

  2. sql:[dbo].[smt_MES_RptProductDaily] 生产日报表

    USE [ChangHongMES_904]GO/****** Object: StoredProcedure [dbo].[smt_MES_RptProductDaily] Script Date: ...

  3. Linux下升级python版本

    转载自:http://lovebeyond.iteye.com/blog/1770476 CentOS下的Python版本一般都比较低,很多应用都需要升级python来完成.我装的centOS的默认的 ...

  4. [置顶] Quartz的DateBuilder详解

    DateBuilder类有两个方法: nextGivenMinuteDate和nextGivenSecondDate: Method: (a)  public static  Date   nextG ...

  5. The Trip PC/UVa IDs: 110103/10137, Popularity: B, Success rate: average Level: 1

    #include<cstdio> #include<iostream> #include<string> #include<algorithm> #in ...

  6. Spring 的两个配置容器的讲解

    容器 是Spring框架的核心,是组件存活的地方.Spring容器使用DI管理所有组成应用系统的组件,协作组件之间建立联.而且, 这些对象简洁易懂,降低耦合性,支持重用,容易被测试. Spring提供 ...

  7. C++ struct与class

    1.相对于C中struct,C++做了很大的扩充.基本上和class 差不多.只有一些细节上的差别. 2.对于成员的默认访问权限,class是private,struct是public.需要注意的是, ...

  8. Codeforces Round #172 (Div. 2) B. Nearest Fraction 二分

    B. Nearest Fraction Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/281/p ...

  9. Codeforces Round #276 (Div. 1) B. Maximum Value 筛倍数

    B. Maximum Value Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/484/prob ...

  10. Codeforces Gym 100571A A. Cursed Query 离线

    A. Cursed QueryTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/gym/100571/problem ...