微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在用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框架在“请求表单”类中还使用“失败规则”(例如,电子邮件已经存在)的http状态422.查看此:http://laravel.com/docs/master/validation

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐