【问题标题】:validation error responses in REST APIREST API 中的验证错误响应
【发布时间】:2026-02-16 00:25:01
【问题描述】:

我正在设计一个 RESTful API,并且想知道验证错误消息的最佳格式是什么。

例如,我的帐户创建端点接受 JSON 对象:

user: {
  first_name: string,
  last_name: string,
  address: {
    street: string,
    city: string,
    zip_code: string
  }
}

我的回复将采用以下格式:

{
    code: 400,  // HTTP code
    message: "Validation failed",  // general message
    type: "validation_failed",  // there are other types of errors as well
    errors: WHAT_DO_I_SHOW_HERE
}

我有几种验证错误消息的选择:

格式 1

errors: {
  last_name: "First name is required",
  address: {
    zip_code: "ZIP code is invalid"
  }
}

或将错误按格式 2 展平

errors: {
  last_name: "First name is required",
  "address.city": "City is required",
  "address.zip_code": "ZIP code is invalid"
}

或者使用数组,其中每个元素可以有字段名、错误代码、错误信息、嵌套错误等。

errors: [
  {
    field: "first_name",
    message: "First name is required",
  },
  {
    field: "address",
    errors: [
      {
        field: "zip_code",
        message: "ZIP code is invalid"
      }
    ]
  }
]

errors: [
  {
    field: "first_name",
    message: "First name is required",
  },
  {
    field: "address.zip_code",
    message: "ZIP code is invalid"
  }
]

显然数组格式更灵活,因为字段名称是可选的,因此它可以容纳与多个字段组合相关的错误(例如,时间间隔的结束时间必须在开始时间之后)。但我的问题是,哪一个更容易被 API 用户使用?

【问题讨论】:

    标签: json rest api error-handling


    【解决方案1】:

    对于在前端 html 工作的我来说,我更愿意将错误格式 2 展平。这对我来说很容易查看它,或者很容易定位要显示的错误。

    敞开心扉倾听他人的意见

    【讨论】:

      【解决方案2】:

      所以您的客户必须检查 HTTP 状态码,如果不是 200 OK,他们就必须检查错误并将 JSON 反序列化到模型对象中?如果出现不同类型的错误(例如 BadRequest、冲突或与 DB 相关的错误)会发生什么?

      为什么不返回一个泛型

      errors: [
        {
          type: "ValidationError", // or an int value from an Enum
          message: "First name is required",
        },
        {
          type: "DBError",
          message: "Connection not found" // you might want to say something more generic here, but at the same time if you don't treat it at all it will bubble up as a 500 internal server error
        }
      ]
      

      当然,这两种情况可能不会同时发生,但您仍然希望您的 API 尽可能通用,以免您的客户在他们的代码中捆绑“if”。

      【讨论】:

        【解决方案3】:

        我希望将错误响应作为一个对象的 array。一个错误数组可以表示每个字段的多个错误。

        errors: [
            {
                field: "name",
                message: "name should be at least 4 characters"
            },
            {
                field: "name",
                message: "name should not begin with a dollar sign ($)"
            },
            {
                // other fields
            }
        ]
        

        对于嵌套字段,我会将其表示为字符串数组。

        errors: [
          {
            field: ["address", "zip_code"],
            message: "ZIP code is invalid"
          }
        ]
        

        【讨论】:

          【解决方案4】:

          也许它有点过时了,但 JSON API 规范说

          错误对象必须以 JSON API 文档顶层错误作为键的数组返回。

          Here is a link

          【讨论】: