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());
}
# 1 楼答案
可以使用ExceptionHandler根据异常定制错误响应。 您还可以像这样重用
DefaultErrorAttributes
和ResponseEntityExceptionHandler
:https://stackoverflow.com/a/64866190/548473另见Using ErrorAttributes in our custom ErrorController
# 2 楼答案
如果您使用的是Spring boot 2.3,请在应用程序中设置以下属性。属性将在响应中添加自定义消息
# 3 楼答案
在控制器中,不要尝试捕捉。相反,直接对方法执行
throws
,如下所示:如果有错误,你会得到你想要的,即
如果要进一步自定义错误响应,可以执行以下操作: