有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在错误spring引导rest api期间自定义HTTP响应消息

我想为HTTP响应定制一条消息,即

{
    "timestamp": "2020-06-30T00:40:58.558+00:00",
    "status": 417,
    "error": "Expectation Failed",
    "message": "",
    "path": "/test/v1/tests/4ae767e1-ae83-66dd-9180-81160f766d90"
}

我想要的不是上面的消息,而是定制的“消息”:

{
    "timestamp": "2020-06-30T00:40:58.558+00:00",
    "status": 417,
    "error": "Expectation Failed",
    "message": "#/test: 8.0 is not higher or equal to 100",
    "path": "/test/v1/tests/4ae767e1-ae83-66dd-9180-81160f766d90"
}

这是我的异常类:

@ResponseStatus(value = HttpStatus.EXPECTATION_FAILED)
public class ThrowError extends Exception {

    private static final long serialVersionUID = 1L;
    
    public ThrowErrorMessage(String message){

        super(message);
    }

以下是控制器中函数的catch块:

catch(Exception e) 
        {   
  //basically I want e.getMessage() to be the value of the "Message" key
            throw new ThrowErrorMessage(e.getMessage()); 
            
        }
        

共 (3) 个答案

  1. # 2 楼答案

    如果您使用的是Spring boot 2.3,请在应用程序中设置以下属性。属性将在响应中添加自定义消息

    server.error.include-message=always
    
  2. # 3 楼答案

    在控制器中,不要尝试捕捉。相反,直接对方法执行throws,如下所示:

    @RestController
    @RequestMapping(value = "/api", 
        consumes = { MediaType.APPLICATION_JSON_VALUE }, 
        produces = { MediaType.APPLICATION_JSON_VALUE })
    public class YourClassController {
        @GetMapping(value = "/{id}")
        public ResponseEntity<ResponseDto> getSomething(
                @PathVariable("id") String id
        ) throws ThrowError {
            
            //your code, for example:
            HttpStatus httpStatus = HttpStatus.OK;
            ResponseDto responseDto = new ResponseDto;
            responseDto.timestamp(LocalDateTime.now())
                .status(status);
    
            //maybe some more code
    
            return new ResponseEntity<>(responseDto, httpStatus);
        }
    }
    
    @JsonPropertyOrder({"timestamp", "status", ...})
    public class ResponseDto implements Serializable {
    
        private static final long serialVersionUID = -7377277424125144224L;
        
        //The fields that you want to return if there is no error, example
        @JsonProperty("timestamp")
        @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
        private LocalDateTime timeStamp;
    
        private Integer status;
        
        //more fields
    
        //getter, setters and so on.
    }
    

    如果有错误,你会得到你想要的,即

    {
        "timestamp": "2020-06-30T00:40:58.558+00:00",
        "status": 417,
        "error": "Expectation Failed",
        "message": "#/test: 8.0 is not higher or equal to 100",
        "path": "/test/v1/tests/4ae767e1-ae83-66dd-9180-81160f766d90"
    }
    

    如果要进一步自定义错误响应,可以执行以下操作:

    @Component
    public class CustomErrorAttributes extends DefaultErrorAttributes {
    
        @Autowired
        private ObjectMapper objectMapper;
    
        @Override
        public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
         
            Map<String, Object> map = super.getErrorAttributes(webRequest, options);
    
            //customize the values of the map here i.e timestamp, status, error, message, path
    
            return map;
        }
    }