java - 如何更改对应@NotNull注解返回的响应JSON

标签 java spring spring-boot jackson

我有一个简单的代码,它在 RequestBody 中不存在 customerId 时返回错误 json。

语音类:

public class OrderVO {

    private int orderId;
    @NotNull(message = "CustomerId Cant be null")
    private Long customerId;
}

Controller 方法:

@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 的原因。

最佳答案

将以下方法添加到您的 Controller 建议注释异常处理程序中:

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

关于java - 如何更改对应@NotNull注解返回的响应JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56135588/

相关文章:

java - 特定环境的spring yml文件

spring-boot - docker部署成功后无法连接本地主机上的应用程序

java - Spring MVC -> JSON 响应

java - 如何向现有 Java Swing 程序添加登录屏幕?

java - 从 Firestore 随机获取文档

java - 从 spring Controller 返回 json 数组

java - Oracle 查询返回为 Hasmap<String, String>

java - Arquillian Spring Tomcat 7 嵌入式 - 模拟 @Configuration 类

java - 无法获取静态图像,Tomcat 8.0.24

spring - 如何安全地截断并重新填充 PostgreSQL 中的表?