我有一个简单的代码,当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的原因。
2 回答

有只小跳蛙
TA贡献1824条经验 获得超8个赞
将以下方法添加到控制器建议带注释的异常处理程序:
@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 }

千万里不及你
TA贡献1784条经验 获得超9个赞
我想我们也可以像这样编写Controller建议,而不需要扩展ResponseEntityExceptionHandler并覆盖它的任何方法
@RestControllerAdvicepublic class GlobalExceptionHandler { @ExceptionHandler(value = { MethodArgumentNotValidException.class }) protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex){ CustomException cex = new CustomException(ex.getBindingResult().getFieldError().getDefaultMessage()); return new ResponseEntity<>(cex, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);}
添加回答
举报
0/150
提交
取消