Json RESTAPI中的验证错误响应

Json RESTAPI中的验证错误响应,json,rest,api,error-handling,Json,Rest,Api,Error Handling,我正在设计一个RESTful API,想知道验证错误消息的最佳格式是什么 例如,我的帐户创建端点接受JSON对象: user: { first_name: string, last_name: string, address: { street: string, city: string, zip_code: string } } 我的答复将采用以下格式: { code: 400, // HTTP code message: "Vali

我正在设计一个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"
      }
    ]
  }
]


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

对于我在前端html中工作的人来说,我更喜欢将错误格式2扁平化。对我来说,查看它会很容易,或者很容易找到要显示的错误


打开以听取其他人的意见

,这样您的客户机就必须检查HTTP状态代码,如果它不正常,他们就必须检查错误并将JSON反序列化到模型对象中?如果出现不同类型的错误(例如,错误请求、冲突或与数据库相关的错误),会发生什么情况

为什么不返回一个泛型

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”。

我更喜欢将错误响应作为对象的数组。错误数组可以表示每个字段的多个错误

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"
  }
]

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

错误对象必须以数组的形式返回,该数组由JSON API文档顶层的错误键控

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