REST:将应用程序错误映射到 HTTP 状态代码 [英] REST: Mapping application errors to HTTP Status codes

查看:39
本文介绍了REST:将应用程序错误映射到 HTTP 状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像这样重用 RFC HTTP 状态代码是否应该被视为良好做法,或者我们应该制作完全映射的新代码> 到我们具体的错误原因?

Is it to be considered good practice to reuse RFC HTTP Status codes like this, or should we be making up new ones that map exactly to our specific error reasons?

我们正在围绕几个遗留应用程序设计 Web 服务 API.

We're designing a web service API around a couple of legacy applications.

除了响应正文中的 JSON/XML 数据结构外,我们还旨在返回对网络缓存开发人员有意义的 HTTP 状态代码.

In addition to JSON/XML data structures in the Response Body, we aim to return HTTP Status Codes that make sense to web caches and developers.

但是您如何将不同类别的错误映射到适当的 HTTP 状态代码?团队中的每个人都同意以下几点:

But how do you go about mapping different classes of errors onto appropriate HTTP Status codes? Everyone on the team agrees on the following:

GET/package/1234 返回 404 Not Found 如果 1234 不存在

GET /package/1234 returns 404 Not Found if 1234 doesn't exist

GET/package/1234/next_checkpoint 返回 400 Bad Request 如果next_checkpoint" 1234 是有效的要求,但 next_checkpont 在这里没有意义......

GET /package/1234/next_checkpoint returns 400 Bad Request if "next_checkpoint" and 1234 are valid to ask for but next_checkpont here doesn't make sense...

等等......但是,在某些情况下,事情需要更具体,而不仅仅是400".- 例如:

and so on... but, in some cases, things needs to be more specific than just "400" - for example:

POST/dispatch/?for_package=1234 返回 412 Precondition Failed 如果/dispatch 和 package 1234 都存在,但 1234 还没有准备好分发.

POST /dispatch/?for_package=1234 returns 412 Precondition Failed if /dispatch and package 1234 both exist, BUT 1234 isn't ready for dispatch just yet.


(HTTP 中的状态代码/1.1WebDAV ext 中的状态代码.)

推荐答案

RESTful 使用 HTTP 意味着您必须保持 API 统一.这意味着您不能添加特定于域的方法(ala GET_STOCK_QUOTE),但也意味着您不能添加特定于域的错误代码(ala 499 Product Out Of Stock).

RESTful use of HTTP means that you must keep the API uniform. This means that you cannot add domain specific methods (ala GET_STOCK_QUOTE) but it also means that you cannot add domain specific error codes (ala 499 Product Out Of Stock).

事实上,HTTP 客户端错误代码是一个很好的设计检查,因为如果您正确设计资源语义,HTTP 错误代码的含义将正确表达任何错误.如果您觉得需要额外的错误代码,那么您的资源设计很可能是错误的.

In fact, the HTTP client error codes are a good design check because if you design your resource semantics properly, the HTTP error code meanings will correctly express any errors. If you feel you need additional error codes, your resource design is likely wrong.

一月

这篇关于REST:将应用程序错误映射到 HTTP 状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆