【问题标题】:How to change response JSON returned corresponding to @NotNull annotation如何更改与@NotNull 注解对应的响应 JSON 返回
【发布时间】:2019-10-01 18:51:47
【问题描述】:

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

【问题讨论】:

  • 您可以使用错误处理来构建自定义响应。在stackoverflow.com/questions/45997775/… 找到了类似的问题
  • @suketup 我已经知道我们可以抛出自定义异常并在 ControllerAdvice 中处理它,但是考虑如果验证所需的字段数 = 20,则检查和抛出异常所需的数量也会增加,使代码看起来很难看。这就是我发布此 Qn 的原因

标签: java spring spring-boot jackson


【解决方案1】:

将以下方法添加到您的控制器通知注释异常处理程序中:

    @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
    }

【讨论】:

  • 对不起。它不适合我。我仍然得到相同的 JSON 结构。目前没有变化。
  • 我还在controllerAdvice上放置了调试点,但是控制没有到达这些方法。
  • @ASharma7 我更新了我的答案。注意覆盖方法
  • 我认为我们可以跳过这个覆盖并保持 controlleradvice 简单。见下面我的回答
  • @ASharma7 是的。但是我们的异常处理程序的父级ResponseEntityExceptionHandler中有一些处理程序我们不需要自己编写
【解决方案2】:

我想我们也可以像这样编写控制器建议,而无需扩展 ResponseEntityExceptionHandler 并覆盖其任何方法

@RestControllerAdvice
public 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);
}

【讨论】:

猜你喜欢
  • 2019-06-30
  • 2013-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-19
  • 2015-12-27
  • 2017-04-05
  • 1970-01-01
相关资源
最近更新 更多