简体   繁体   English

针对业务异常的REST API设计

[英]REST API design on business exceptions

There is a debate in our team regarding how the REST API should behave when the server encounters a business exception (maybe a validation or some other business related exception). 我们的团队中有一个辩论,涉及当服务器遇到业务异常(可能是验证或其他与业务相关的异常)时REST API的行为。

Part of the team claims that the server should send 200 as status every time, with a flag and code on the response. 该小组的一部分声称服务器应每次发送200作为状态,并在响应上带有标志和代码。 As far as I know, this approach breaks the HTTP status codes principle and the Richardson Maturity Model . 据我所知,这种方法违反了HTTP状态码原理和Richardson成熟度模型

The other part of the team wants to map business exceptions to HTTP status codes. 团队的另一部分希望将业务异常映射到HTTP状态代码。 Is this approach following the REST principles or business exceptions are not covered there? 是否遵循REST原则的这种方法或业务异常不在此处?

I'm just curious to hear other opinions regarding this debate. 我很好奇,希望听到有关这场辩论的其他意见。

We solved the issue in our team by "enjoying" both worlds: 我们通过“享受”两个世界来解决团队中的问题:

We map the business exceptions to the closest HTTP code. 我们将业务异常映射到最接近的HTTP代码。 For example if a user asks for an entity that is not found, we give out 404. 例如,如果用户要求一个未找到的实体,我们给出404。

In the response we give an error JSON that holds all the business related information similar to this one: 在响应中,我们给出一个错误JSON,其中包含与此相似的所有与业务相关的信息:

[
    {
        "code": 4004, // This is our application specific code in thousands instead of hundreds
        "message": "entity <bla bla> not found",
        "stack": ... // The stack trace for debugging
        "headers": ... // The request headers also for debugging
    },
    {
        ... // Another error JSON here
    }
]

Note that it is an array cause sometimes we find more than 1 error in the input validation logic. 请注意,这是一个数组原因,有时我们会在输入验证逻辑中发现多个错误。

REST supports the usage of standards over custom solutions. REST支持在自定义解决方案上使用标准。 So if you use HTTP as the underlying protocol, then I think you should map your error types to HTTP status headers instead of developing a custom solution which does not meat with the HTTP standard. 因此,如果您使用HTTP作为基础协议,那么我认为您应该将错误类型映射到HTTP状态标头,而不是开发一个不符合HTTP标准的自定义解决方案。 This is part of the uniform interface / self descriptive message constraint. 这是统一接口/自我描述消息约束的一部分。 The text does not mention the HTTP status header, but the HTTP methods and other headers are part of it as examples of the uniform interface which applies standards, so I think the intent is very clear... 文本没有提到HTTP状态标头,但是HTTP方法和其他标头作为应用标准的统一接口示例的一部分,因此我认为其意图非常明确...

Ofc. Ofc。 it is allowed to send a more specific message body about the error along with the proper status header. 允许发送有关错误的更具体的消息正文以及正确的状态标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM