gpt4 book ai didi

php - 如果无法执行操作,API 应该返回什么?

转载 作者:搜寻专家 更新时间:2023-10-31 20:37:16 25 4
gpt4 key购买 nike

我正在用 PHP 为移动应用程序编写 API。其中一个端点 create-user.php 应该用于向 User 表添加新记录。如果应用程序试图创建副本怎么办?我可以捕获它并返回一条错误消息(顺便说一句?)。问题是,我是否也应该返回一个结构如下的 JSON:

{
"status": "The email already exists"
}

...向客户提供有关问题所在的更多信息?还是我应该只使用错误代码,仅此而已?

最佳答案

返回http状态422和错误信息

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions. page statistics

具体来说:

422 status code feels much more appropriate. The server understands what you're trying to do; and it understands the data that you're submitting; it simply won't let that data be processed.

阅读更多来自 Ben Nadel 的文章:http://www.bennadel.com/blog/2434-http-status-codes-for-invalid-data-400-vs-422.htm

此外,Laravel 框架在其 Request Form 类中还使用“失败规则”(例如电子邮件已存在)的 http 状态 422。看到这个:http://laravel.com/docs/master/validation

关于php - 如果无法执行操作,API 应该返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32052760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com