我正在用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.
此外,Laravel框架在“请求表单”类中还使用“失败规则”(例如,电子邮件已经存在)的http状态422.查看此:http://laravel.com/docs/master/validation
标签:mobile,api,backend,json,php
来源: https://codeday.me/bug/20191119/2039413.html