如何更改与@NotNull批注对应的响应JSON返回 [英] How to change response JSON returned corresponding to @NotNull annotation

查看:118
本文介绍了如何更改与@NotNull批注对应的响应JSON返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的代码,当RequestBody中没有customerId时,返回错误json.

I have a simple code which return error json when customerId is not present in the RequestBody.

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的结构如下所示:

Currently when customerId is not present in the RequestBody, the structure of JSON returned is as shown below:

{
    "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结构:

how can I change the above Json structure returned by @Notnull to JSON structure shown below :

{
    "timestamp": "2019-05-14T17:08:01.318+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "CustomerId Cant be null"
}

编辑-我已经知道我们可以抛出自定义异常并在ControllerAdvice中对其进行处理,但是请考虑是否验证所需的字段数= 20,即检查null&所需的代码量.抛出异常也会扩大规模,使代码看起来难看.这就是为什么我发布此Qn的原因.

Edit - I already know that we can throw custom exception and handle it in ControllerAdvice, but consider if number of fields required for validation = 20, the amount of code required to check for null & throw exception would also scale up , making code look ugly. That is why I have posted this Qn.

推荐答案

将以下方法添加到带注释的控制器建议异常处理程序中:

Add methods below to your controller advice annotated exception handler:

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

这篇关于如何更改与@NotNull批注对应的响应JSON返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆