REST service: The proper way of returning exception

后端 未结 3 1108
太阳男子
太阳男子 2021-02-05 20:23

I use Jersey API for my REST service. My question is: Is there a more elegant way of returning exceptions in a JSON form? Is it better to concern myself with creating a json obj

3条回答
  •  囚心锁ツ
    2021-02-05 20:57

    You can create a class like the one below to represent an error,

    @JsonPropertyOrder({ "code", "field", "message" })
    public class ErrorInfo {
    
        private String code;
    
        private String field;
    
        private String message;
    
        public String getCode() {
            return code;
        }
    
        public void setCode(String code) {
            this.code = code;
        }
    
        public String getField() {
            return field;
        }
    
        public void setField(String field) {
            this.field = field;
        }
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
    }
    

    You can create a class which extends an exception like this,

    public class InvalidInputException extends RuntimeException {
    
        private static final long serialVersionUID = -5027121014723838738L;
    
        private List errors;
    
        public List getErrors() {
            return this.errors;
        }
    
        public InvalidInputException(List errors) {
            super();
            this.errors = errors;
        }
    
        public InvalidInputException(String message, List errors) {
            super(message);
            this.errors = errors;
        }
    
    }
    

    And have a exception mapper, where you can convert the List to json and return to the user with http status code 400 (Bad Request).

    @Provider
    public class InvalidInputExceptionMapper implements ExceptionMapper {
    
        @Override
        @Produces(MediaType.APPLICATION_JSON)
        public Response toResponse(InvalidInputException e) {
    
            ResponseBuilder rb = Response.status(Status.BAD_REQUEST);
    
            rb.entity(e.getErrors());
            return rb.build();   
        }
    }
    

    Http Response will be,

    HTTP/1.1 400 BAD REQUEST
    {
    "errors": [{
        "error": {
            "code": "100",
            "field": null,
            "message": "Name is required"
        },
        "error": {
            "code": "100",
            "field": null,
            "message": "Age is required"
        }
    }]
    

    }

提交回复
热议问题