传递无效的ID到一个端点:如何处理这种情况?

huangapple go评论104阅读模式
英文:

Passing invalid ID to an endpoint: how to handle such a case?

问题

考虑处理 /v1/api/people/{id} 端点的 GET、PUT 和 DELETE 操作,其中 id 是一个整数。

我在思考以下两种情况通常应该如何处理?

a). 当传递的 id 在数据库中不存在,例如 id = 100,但没有这样的实体

b). 当传递的 id 类型错误,例如它是一个字符串 "oops"

想象一下,上述两种错误实际上永远不会发生,就实际应用而言(因为例如应用具有“正确”的工作流程和一些客户端验证)。

然而,我仍然可以在诸如 Postman 中引发上述错误,或者如果将来发生了某些变化,对吗?我希望防止将来出现这些错误。

是应该保留为 HTTP 500,还是应该处理为 HTTP 400 或 HTTP 404?HTTP 500 是否可接受?

英文:

Consider /v1/api/people/{id} endpoint handling GET, PUT and DELETE operations, where id is an integer.

I am wondering about how the below two cases should typically be handled?

a). when passed id does not exists in database, e.g. id = 100 but there is no entity of such id

b). when passed id is of wrong type e.g. it is a string "oops"

Imagine that both of above errors never actually happen as far as the real application is concerned (because e.g. application has "correct" workflow and some client-side validation).

However, I can still cause the above errors in let's say Postman or if something changes in the future, right? I want to prevent those errors in the future.

Should it be left as HTTP 500 or perhaps should it be handled as HTTP 400 or HTTP 404? Is HTTP 500 ever acceptable?

答案1

得分: 3

HTTP 500 - 应该被用作内部服务器错误,意味着服务器端发生了意外情况.. 上述错误理应是验证的一部分,因为它们是已知的场景

a) 当传递的 id 在数据库中不存在,例如 id = 100,但是没有这样 id 的实体

  • 在这种情况下,您应该返回 404(未找到),并显示错误消息,例如'资源 id 100 不存在于删除/更新等操作中',以使用户可以理解

b) 当传递的 id 类型错误,例如它是一个字符串 "oops"

  • 在这种情况下,您应该显示 400(错误请求),因为用户未按照约定传递资源 id 值。
英文:

HTTP 500 - should be used as Internal Server Error meaning something unexpected happened in server side .. above errors should be part of validation ideally since they are known scenarios

a). when passed id does not exists in database, e.g. id = 100 but there is no entity of such id

  • here you should return 404(Not Found) with error msg like 'resource with id 100 not present for deletion/update etc' to make it user friendly

b). when passed id is of wrong type e.g. it is a string "oops"

  • here you should show 400 (BadRequest) since user is not passing value as per agreement that is resource id.

huangapple
  • 本文由 发表于 2020年8月19日 21:42:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63488324.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定