我有一个简单的代码,当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和throw异常所需的代码量也会扩大,使代码看起来很难看。这就是我发布这个Qn的原因。
有只小跳蛙
千万里不及你
相关分类