首页 > 解决方案 > 在错误spring boot 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()); 
            
        }
        

标签: javaspringspring-bootresthttp

解决方案


如果您使用的是 Spring boot 2.3,那么在 application.properties 中设置以下属性将在响应中添加您的自定义消息。

server.error.include-message=always

推荐阅读