我有一个简单的代码,当 RequestBody 中不存在 customerId 时,它返回错误 json。
VO 类:
public class OrderVO {
private int orderId;
@NotNull(message = "CustomerId Cant be null")
private Long customerId;
}
控制器方法:
@RequestMapping(value="/testOrderbyOrderid", method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
public void testOrderJson (@Valid @RequestBody OrderVO orderVO ) {
}
目前当RequestBody中不存在customerId时,返回的JSON结构如下所示:
{
"timestamp": "2019-05-14T17:08:01.318+0000",
"status": 400,
"error": "Bad Request",
"errors": [
{
"codes": [ ],
"arguments": [ ],
"defaultMessage": "CustomerId Cant be null",
"objectName": "orderVO",
"field": "customerId",
"rejectedValue": null,
"bindingFailure": false,
"code": "NotNull"
}
],
"message": "Validation failed for object='orderVO'. Error count: 1",
"path": "/testOrderbyOrderid"
}
如何将 @Notnull 返回的上述 Json 结构更改为如下所示的 JSON 结构:
{
"timestamp": "2019-05-14T17:08:01.318+0000",
"status": 400,
"error": "Bad Request",
"message": "CustomerId Cant be null"
}
编辑 - 我已经知道我们可以抛出自定义异常并在 ControllerAdvice 中处理它,但考虑一下,如果验证所需的字段数 = 20,则检查 null 和抛出异常所需的代码量也会增加,使代码看起来很难看。这就是我发布此 Qn 的原因。