8000 [Docs] Add documentation for showing errors (#121) · AxonDivisionDev/laravel-json-api@94c2f96 · GitHub
[go: up one dir, main page]

Skip to content

Commit 94c2f96

Browse files
GIANTCRABlindyhopchris
authored andcommitted
[Docs] Add documentation for showing errors (cloudcreativity#121)
Add a chapter on custom errors
1 parent 58ab6ec commit 94c2f96

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

docs/features/custom-errors.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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+
```

mkdocs.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ pages:
1717
- Controllers: custom/controllers.md
1818
- Digging Deeper:
1919
- Inclusion: features/inclusion.md
20+
- Custom Errors: features/custom-errors.md
2021
- Broadcasting: features/broadcasting.md
2122
- Helpers: features/helpers.md
2223
- HTTP Clients: features/http-clients.md

0 commit comments

Comments
 (0)
0