1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Flugg\Responder\Traits; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use Flugg\Responder\Exceptions\ApiException; |
7
|
|
|
use Flugg\Responder\Exceptions\ResourceNotFoundException; |
8
|
|
|
use Flugg\Responder\Exceptions\UnauthenticatedException; |
9
|
|
|
use Flugg\Responder\Exceptions\UnauthorizedException; |
10
|
|
|
use Flugg\Responder\Exceptions\ValidationFailedException; |
11
|
|
|
use Illuminate\Auth\Access\AuthorizationException; |
12
|
|
|
use Illuminate\Auth\AuthenticationException; |
13
|
|
|
use Illuminate\Database\Eloquent\ModelNotFoundException; |
14
|
|
|
use Illuminate\Http\JsonResponse; |
15
|
|
|
use Illuminate\Validation\ValidationException; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Use this trait in your exceptions handler to give you access to methods you may |
19
|
|
|
* use to let the package catch and handle any API exceptions. |
20
|
|
|
* |
21
|
|
|
* @package Laravel Responder |
22
|
|
|
* @author Alexander Tømmerås <[email protected]> |
23
|
|
|
* @license The MIT License |
24
|
|
|
*/ |
25
|
|
|
trait HandlesApiErrors |
26
|
|
|
{ |
27
|
|
|
/** |
28
|
|
|
* Transform Laravel exceptions into API exceptions. |
29
|
|
|
* |
30
|
|
|
* @param Exception $e |
31
|
|
|
* @return void |
32
|
|
|
* @throws UnauthenticatedException |
33
|
|
|
* @throws UnauthorizedException |
34
|
|
|
* @throws ResourceNotFoundException |
35
|
|
|
* @throws ValidationFailedException |
36
|
|
|
*/ |
37
|
|
|
protected function transformExceptions( Exception $e ) |
38
|
|
|
{ |
39
|
|
|
if ( $e instanceof AuthenticationException ) { |
40
|
|
|
throw new UnauthenticatedException(); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
if ( $e instanceof AuthorizationException ) { |
44
|
|
|
throw new UnauthorizedException(); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
if ( $e instanceof ModelNotFoundException ) { |
48
|
|
|
throw new ResourceNotFoundException(); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
if ( $e instanceof ValidationException ) { |
52
|
|
|
throw new ValidationFailedException( $e->validator ); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Renders any API exception into a JSON error response. |
58
|
|
|
* |
59
|
|
|
* @param ApiException $e |
60
|
|
|
* @return JsonResponse |
61
|
|
|
*/ |
62
|
|
|
protected function renderApiError( ApiException $e ):JsonResponse |
63
|
|
|
{ |
64
|
|
|
$message = $e instanceof ValidationFailedException ? $e->getValidationMessages() : $e->getMessage(); |
65
|
|
|
|
66
|
|
|
return app( 'responder' )->error( $e->getErrorCode(), $e->getStatusCode(), $message ); |
67
|
|
|
} |
68
|
|
|
} |