rrd108 / cakephp-json-api-exception
CakePHP 的 JsonApiException 插件
1.0.0
2023-11-11 11:44 UTC
Requires
- php: >=8.0
- cakephp/cakephp: ^5.0
Requires (Dev)
- phpunit/phpunit: ^10.1
README
使您的 CakePHP 5 JSON REST API 错误响应更具描述性。
要支持 CakePHP 4,请使用 CakePHP 4 分支
如果您需要一个简单的解决方案来为 CakePHP JSON REST API 实现令牌身份验证,请查看此: CakePHP API Token Authenticator
安装
您可以使用 composer 将此插件安装到您的 CakePHP 应用程序中。
推荐的安装方法是
composer require rrd108/cakephp-json-api-exception
然后,要加载插件,可以运行以下命令
bin/cake plugin load JsonApiException
或者手动将以下行添加到您的应用 src/Application.php
文件中的 bootstrap()
函数中
$this->addPlugin('JsonApiException');
完成 :)
如何使用
假设您有一个 CakePHP JSON REST API,并且您想拥有更详细的消息和适当的响应代码。
// for example in /src/Controller/UsersController.php slightly change the baked add function use JsonApiException\Error\Exception\JsonApiException; public function add() { $user = $this->Users->newEmptyEntity(); if ($this->request->is('post')) { $user = $this->Users->patchEntity($user, $this->request->getData()); if (!$this->Users->save($user)) { throw new JsonApiException($user, 'Save failed'); // throw new JsonApiException($user, 'Save failed', 418); // you can set the response's status code in the 3rd parameter } } $this->set(compact('user')); $this->viewBuilder()->setOption('serialize', ['user']); }
如果保存失败,您将得到如下响应。
{ "message": "Save failed", "url": "/users.json", "line": 12, "errorCount": 1, "errors": { "password": { "_required": "This field is required" } } }
您也可以使用实体数组。
// for example in /src/Controller/UsersController.php slightly change the baked add function use JsonApiException\Error\Exception\JsonApiException; public function bulkAdd() { $users = $this->Users->newEntities($this->request->getData()); if (!$this->Users->saveMany($users)) { throw new JsonApiException($users, 'Errors in request data'); } $this->set(compact('users')); $this->viewBuilder()->setOption('serialize', ['users']); }
如果保存失败,您将得到如下响应。由于此时我们还没有实体的 id
,错误消息中不能包含它。所以如果实体没有任何错误,errors
数组将包含一个空数组。因此,实体的数量将匹配错误条目的数量,实体 #3 的错误消息将是错误数组的第三个元素。
{ "message": "Errors in request data", "url": "/users.json", "line": 12, "errorCount": 2, "errors": [ { "name": { "_empty": "name is required" } }, { "name": { "_empty": "name is required" } } ] }