首页 > 解决方案 > How to throw Spring @Valid "exception"?

问题描述

I'm using Spring to build my REST api. One of my methods is decorated with @Valid. This produces a JSON that looks like this:

{
  "timestamp": "2019-11-04T19:07:08.387+0000",
  "status": 400,
  "error": "Bad Request",
  "errors": [
    {
      "codes": [
        "NotNull.customer.firstName",
        "NotNull.firstName",
        "NotNull.java.lang.String",
        "NotNull"
      ],
      "arguments": [
        {
          "codes": [
            "customer.firstName",
            "firstName"
          ],
          "arguments": null,
          "defaultMessage": "firstName",
          "code": "firstName"
        }
      ],
      "defaultMessage": "must not be null",
      "objectName": "customer",
      "field": "firstName",
      "rejectedValue": null,
      "bindingFailure": false,
      "code": "NotNull"
    }
  ],
  "message": "Validation failed for object='customer'. Error count: 1",
  "path": "/customers"
}

Doing a Google search, to produce a HTTP 400 error, I'm supposed to throw ResponseStatusException(HttpStatus.BAD_REQUEST);

This produces a JSON like this:

{
  "timestamp": "2019-11-04T19:08:02.408+0000",
  "status": 400,
  "error": "Bad Request",
  "message": "400 BAD_REQUEST",
  "path": "/customers"
}

The message is easy to change obviously, but I'm more asking about how to get the Errors array. That doesn't seem to be in ResponseStatusException?

I can recreate it pretty easily, but I was hoping there was one built already?

EDIT: This isn't input validation per say... this is throwing an error FOR the input, but I need to hit the database first to do the actual validation, so that part is in my service layer and throws an internal exception if it isn't valid.

标签: javaspring

解决方案


如果您使用的是验证器,那么您可以使用配置文件来自定义错误,例如validator.properties


推荐阅读