简体   繁体   English

REST API错误返回,是否包含HTTP状态代码

[英]REST API error return, include HTTP status code or not

I'm working on an restful API back end, and we only use json as content type. 我正在开发一个宁静的API后端,并且我们仅使用json作为内容类型。 And There are two ways of performing error response as I know: 据我所知,有两种执行错误响应的方法:

  1. HTTP status code is always 200, and the returning json should contain error code and error message. HTTP状态代码始终为200,返回的json应包含错误代码和错误消息。
  2. Treat HTTP status code as part of our API, we may pick HTTP error code(4XX) to corresponding error condition. 将HTTP状态代码视为我们API的一部分,我们可能会根据相应的错误情况选择HTTP错误代码(4XX)。 And we can include a json document in the payload to includes a sub-code and a descriptive comment. 我们可以在有效负载中包含一个json文档,以包含一个子代码和一个描述性注释。

I want to know which one is more idiom for a restful service? 我想知道哪一种更适合休闲服务?

You need to use both. 您需要同时使用两者。

  1. HTTP Status : Use this to process the status of the request. HTTP状态 :使用它来处理请求的状态。 For example, if you query a DB and you find no entries, you'll still return 200. If the user is not authorized, 403, if number of SQL connections exceed, 500, and so on. 例如,如果查询数据库,但没有找到条目,则仍将返回200。如果未授权用户,则返回403,如果SQL连接数超过500,以此类推。

  2. API Status : If the DB request succeed and you find no entries, include a custom field in your json {status: NO_ENTRIES } or { status: DEPRECATED_API } . API状态 :如果数据库请求成功,但您找不到任何条目,请在json {status: NO_ENTRIES }{ status: DEPRECATED_API }包含一个自定义字段。 In these cases, the response code will still be 200. 在这些情况下,响应代码仍为200。

Generally speaking, I would not advocate for always returning a 200. There are failure scenarios that match commonly accepted status codes. 一般来说,我不主张总是返回200。有些失败情况与普遍接受的状态代码相匹配。 Above, someone mentioned 403, which you deliver when access is denied. 上面提到了有人403,当访问被拒绝时您将提供它。 And 500 is typically issued by the web/app server when things really go south. 当事情真的很严重时,通常由Web /应用程序服务器发出500。 And 404 if either a record is not found for a resource. 404,如果找不到资源的任何记录。

So, I do advocate for: 因此,我主张:

  1. Going with at least 200, 403, 404, 500 至少搭配200、403、404、500
  2. Providing as verbose error details as possible in your JSON error response 在JSON错误响应中提供尽可能详细的错误详细信息
  3. Documenting every error code your API might deliver - HTTP status codes and every sub-condition error 记录您的API可能传递的每个错误代码-HTTP状态代码和每个子条件错误

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

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