JAX/Jersey Custom error code in Response

前端 未结 2 1830
猫巷女王i
猫巷女王i 2020-12-08 01:10

In Jersey, how can we \'replace\' the status string associated with a known status code?

e.g.

return Response.status(401).build();

2条回答
  •  天命终不由人
    2020-12-08 01:46

    I'm not sure JSR 339: JAX-RS 2.0: The Java API for RESTful Web Services already covered this or not.

    You might have to extend the Response.StatusType for this.

    public abstract class AbstractStatusType implements StatusType {
    
        public AbstractStatusType(final Family family, final int statusCode,
                                  final String reasonPhrase) {
            super();
    
            this.family = family;
            this.statusCode = statusCode;
            this.reasonPhrase = reasonPhrase;
        }
    
        protected AbstractStatusType(final Status status,
                                     final String reasonPhrase) {
            this(status.getFamily(), status.getStatusCode(), reasonPhrase);
        }
    
        @Override
        public Family getFamily() { return family; }
    
        @Override
        public String getReasonPhrase() { return reasonPhrase; }
    
        @Override
        public int getStatusCode() { return statusCode; }
    
        public ResponseBuilder responseBuilder() { return Response.status(this); }
    
        public Response build() { return responseBuilder().build(); }
    
        public WebApplicationException except() {
            return new WebApplicationException(build());
        }
    
        private final Family family;
        private final int statusCode;
        private final String reasonPhrase;
    }
    

    And here are some extended statust types.

    public class BadRequest400 extends AbstractStatusType {
    
        public BadRequest400(final String reasonPhrase) {
            super(Status.BAD_REQUEST, reasonPhrase);
        }
    }
    
    public class NotFound404 extends AbstractStatusType {
    
        public NotFound404(final String reasonPhrase) {
            super(Status.NOT_FOUND, reasonPhrase);
        }
    }
    

    This is how I do.

    @POST
    public Response create(final MyEntity entity) {
    
        throw new BadRequest400("bad ass").except();
    }
    
    @GET
    public MyEntity read(@QueryParam("id") final long id) {
    
        throw new NotFound404("ass ignorant").except();
    }
    
    // Disclaimer
    // I'm not a native English speaker.
    // I don't know what 'bad ass' or 'ass ignorant' means.
    

提交回复
热议问题