|
1 | 1 | # JsonApiException plugin for CakePHP
|
2 | 2 |
|
| 3 | +Make your CakePHP 4 JSON REST API response more descriptive on errors. |
| 4 | + |
| 5 | +If you want a simple solution for token authentication for a CakePHP JSON REST API, then check this: [CakePHP API Token Authenticator](https://github.com/rrd108/api-token-authenticator) |
| 6 | + |
3 | 7 | ## Installation
|
4 | 8 |
|
5 | 9 | You can install this plugin into your CakePHP application using [composer](https://getcomposer.org).
|
6 | 10 |
|
7 |
| -The recommended way to install composer packages is: |
| 11 | +The recommended way to install is: |
8 | 12 |
|
9 | 13 | ```
|
10 | 14 | composer require rrd108/cakephp-json-api-exception
|
11 | 15 | ```
|
12 | 16 |
|
| 17 | +Then, to load the plugin either run the following command: |
| 18 | + |
13 | 19 | ```
|
14 | 20 | bin/cake plugin load JsonApiException
|
15 | 21 | ```
|
| 22 | + |
| 23 | +or manually add the following line to your app's `src/Application.php `file's `bootstrap()` function: |
| 24 | + |
| 25 | +```php |
| 26 | +$this->addPlugin('JsonApiException'); |
| 27 | +``` |
| 28 | + |
| 29 | +done :) |
| 30 | + |
| 31 | +## How to use |
| 32 | + |
| 33 | +Assuming you have a CakePHP JSON REST API and you want to have more informative error messages and proper response codes. |
| 34 | + |
| 35 | +```php |
| 36 | +// for example in /src/Controller/UsersController.php slightly change the baked add function |
| 37 | +use JsonApiException\Error\Exception\JsonApiException; |
| 38 | + |
| 39 | +public function add() |
| 40 | +{ |
| 41 | + $user = $this->Users->newEmptyEntity(); |
| 42 | + if ($this->request->is('post')) { |
| 43 | + $user = $this->Users->patchEntity($user, $this->request->getData()); |
| 44 | + if (!$this->Users->save($user)) { |
| 45 | + throw new JsonApiException($user, 'Save failed'); |
| 46 | + } |
| 47 | + } |
| 48 | + $this->set(compact('user')); |
| 49 | + $this->viewBuilder()->setOption('serialize', ['user']); |
| 50 | +} |
| 51 | +``` |
| 52 | + |
| 53 | +If the save failed you will get a response like this. |
| 54 | + |
| 55 | +```json |
| 56 | +{ |
| 57 | + "message": "Save failed", |
| 58 | + "url": "/users.json", |
| 59 | + "line": 12, |
| 60 | + "errorCount": 1, |
| 61 | + "errors": { |
| 62 | + "password": { |
| 63 | + "_required": "This field is required" |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | +``` |
0 commit comments