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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...