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. 修改浏览器accept使支持@ResponseBody

    原始:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 application/json,text/javascript, ...

  2. MVC神韵---你想在哪解脱!(十七)

    实现针对数据的CRUD操作 首先,让我们来看一下如何实现一条数据的明细信息视图.为了更好地体会这一功能,首先我们在前文所述的电影清单视图(Views文件夹下面的Movies文件夹下面的Index.cs ...

  3. Unity3D - 关于Dynamic和Static

    含有Collider和RigidBody的GameObject, Unity视之为Dynamic 含有Collider的GameObject, Unity视之为Static 如果Static的物体发生 ...

  4. Codeforces Gym 100733A Shitália 计算几何

    ShitáliaTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hust.edu.cn/vjudge/contest/view.acti ...

  5. androidstudio构建(或导入)工程(不用gradle)

    获取源代码: ---assets ---libs ---res ---src 先备份AndroidManifest.xml,然后工程中只保留这四个文件夹,其他文件删除, 然后在studio中导入工程, ...

  6. swift3.0 中NSNotification 的使用

    swift3.0 有很大变化,其中之一就是NSNotification使用跟原来不一样,以前NSNotification name是String:3.0中定义了一个类型NSNotification.n ...

  7. thinkphp中的分表方法

    public function getPartitionTableName($data=array()) { // 对数据表进行分区 if(isset($data[$this->partitio ...

  8. android145 360 进程管理

    package com.itheima.mobileguard.activities; import java.util.ArrayList; import java.util.List; impor ...

  9. php引入公用部分html出现了一行空白(原创)

    在导入公用部分html(客服信息)时,莫名其妙出现了一行空白,样式,html均无问题 后来才发现是html多了一行空白 <div class="ad-module-item3 fn-m ...

  10. java 开源缓存框架--转载

    原文地址:http://www.open-open.com/13.htm  JBossCache/TreeCache  JBossCache是一个复制的事务处理缓存,它允许你缓存企业级应用数据来更好的 ...