我有一个简单的代码,当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。
答案 0 :(得分:3)
将以下方法添加到带注释的异常通知处理程序的控制器建议中:
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status,
WebRequest request) {
//return your custom error
//you can access to field errors using
//ex.getBindingResult().getFieldErrors()
}
@ExceptionHandler(value = { javax.validation.ConstraintViolationException.class })
protected ResponseEntity<Object> handleConstraintViolation(
javax.validation.ConstraintViolationException ex) {
//return your custom error message
}
@ExceptionHandler(value = { org.hibernate.exception.ConstraintViolationException.class })
protected ResponseEntity<Object> handleHibernateConstraintViolation(
org.hibernate.exception.ConstraintViolationException ex) {
//return your custom error message
}
答案 1 :(得分:1)
我想我们也可以这样编写Controller建议,而无需扩展ResponseEntityExceptionHandler并覆盖其任何方法
sphinx-build -M foo . _build