2016-09-29 102 views
0

我在设计一个RESTful API并想知道验证错误消息的最佳格式是什么。REST 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" 
    } 
] 

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

回答

0

对于我在前端html工作的人来说,我更喜欢将错误格式2展平。对于我来说,它很容易查找,或者容易定位错误来显示。

打开听取别人的意见

0

所以,你的客户会检查HTTP状态代码,如果它不是200 OK,他们不得不考虑的错误和反序列化JSON到模型对象?如果存在其他类型的错误(例如,BadRequest,Conflict或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尽可能的通用,从捆绑起来饶你的客户“如果” s在他们的代码中。