zoukankan      html  css  js  c++  java
  • Jersey(1.19.1)

    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.

  • 相关阅读:
    BEGINNING SHAREPOINT&#174; 2013 DEVELOPMENT 第14章节--使用Office Services开发应用程序 总结
    修改sepolicy后编译出现‘Error while expanding policy’【转】
    memalign的作用【转】
    Linux 使用statvfs读取文件系统信息
    strerror函数的总结【转】
    UFS 介绍 1[【转】
    EMMC 介绍【转】
    何为TLC、MLC、SLC?【转】
    赞 ( 84 ) 微信好友 新浪微博 QQ空间 180 SSD故事会(14):怕TLC因为你不了解!【转】
    RPMB分区介绍【转】
  • 原文地址:https://www.cnblogs.com/huey/p/5399581.html
Copyright © 2011-2022 走看看