java - 在错误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());
}
解决方案
如果您使用的是 Spring boot 2.3,那么在 application.properties 中设置以下属性将在响应中添加您的自定义消息。
server.error.include-message=always
推荐阅读
- python - 在抓取网络的循环内发出连接数据名
- wpf - 无论是否有焦点,如何始终显示选定行的蓝色?
- java - 有没有办法用方法创建/定义 ArrayCopy
- laravel - 登录 Laravel 后 Session ID 发生变化
- unity3d - 添加 Google Ads 中介时 Android 资源链接失败 (Unity)
- android - Android FragmentManager:自定义动画显示错误的退出片段
- php - 使用未定义的常量 admin - 假定为“admin”(这将在 PHP 的未来版本中引发错误)
- apache-spark - Pyspark:创建滞后列
- r - R:如何使用行值数据框重命名列
- sql - 嵌套属性为空时的JPA查询排序