|
| 1 | +# Custom Errors |
| 2 | + |
| 3 | +## Introduction |
| 4 | + |
| 5 | +This package allows you to return [JSON API error objects](http://jsonapi.org/format/1.0/#error-objects) which can include various information about what went wrong. |
| 6 | + |
| 7 | +## Custom Errors In Controllers |
| 8 | + |
| 9 | +This is particularly useful for errors that you have to manually present to the user through the controller. In order to magically return errors, you would need to use the `ErrorsAwareTrait`. |
| 10 | + |
| 11 | + |
| 12 | +Below is an example of a scenario which a user fails to login due to incorrect credentials. |
| 13 | + |
| 14 | +```php |
| 15 | +namespace App\Http\Controllers\Api\V1; |
| 16 | + |
| 17 | +use CloudCreativity\JsonApi\Contracts\Http\Requests\RequestInterface as JsonApiRequest; |
| 18 | +use CloudCreativity\JsonApi\Document\Error; |
| 19 | + |
| 20 | +class JsonWebTokensController extends Controller |
| 21 | +{ |
| 22 | + protected function guard() |
| 23 | + { |
| 24 | + return Auth::guard('jwt'); |
| 25 | + } |
| 26 | + |
| 27 | + public function create(JsonApiRequest $request) |
| 28 | + { |
| 29 | + $resource_attributes = $request->getDocument()->getResource()->getAttributes(); |
| 30 | + $credentials = [ |
| 31 | + 'email' => $resource_attributes->email, |
| 32 | + 'password' => $resource_attributes->password, |
| 33 | + ]; |
| 34 | + |
| 35 | + if ($this->guard()->attempt($credentials)) { |
| 36 | + // Success! |
| 37 | + } else { |
| 38 | + // Incorrect login details |
| 39 | + return $this->reply()->errors(Error::create([ |
| 40 | + 'status' => 422, |
| 41 | + 'title' => 'Login failed.', |
| 42 | + 'detail' => 'These credentials do not match our records.' |
| 43 | + ])); |
| 44 | + |
| 45 | + } |
| 46 | + } |
| 47 | +} |
| 48 | +``` |
| 49 | + |
| 50 | +And the response given would be the following: |
| 51 | + |
| 52 | +```json |
| 53 | +{ |
| 54 | + "errors": [ |
| 55 | + { |
| 56 | + "status": "422", |
| 57 | + "title": "Login failed.", |
| 58 | + "detail": "These credentials do not match our records." |
| 59 | + } |
| 60 | + ] |
| 61 | +} |
| 62 | +``` |
0 commit comments