|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace InnoFlash\LaraStart\Traits; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Http\Request; |
|
6
|
|
|
use Illuminate\Validation\ValidationException; |
|
7
|
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; |
|
8
|
|
|
use Symfony\Component\Routing\Exception\RouteNotFoundException; |
|
9
|
|
|
|
|
10
|
|
|
trait ExceptionsTrait |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* Class - error message key maps. |
|
14
|
|
|
* @var array |
|
15
|
|
|
*/ |
|
16
|
|
|
private array $errorMessages = [ |
|
17
|
|
|
NotFoundHttpException::class => 'Invalid route', |
|
18
|
|
|
RouteNotFoundException::class => 'Authorization headers missing', |
|
19
|
|
|
]; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Class - error code key maps. |
|
23
|
|
|
* @var array |
|
24
|
|
|
*/ |
|
25
|
|
|
private array $errorCodes = [ |
|
26
|
|
|
ValidationException::class => 422, |
|
27
|
|
|
RouteNotFoundException::class => 401, |
|
28
|
|
|
]; |
|
29
|
|
|
|
|
30
|
|
|
public function apiExceptions(Request $request, $exception, bool $rawError = false) |
|
31
|
|
|
{ |
|
32
|
|
|
if ($rawError) { |
|
33
|
|
|
return parent::render($request, $exception); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
if (in_array('getMessage', get_class_methods($exception)) && strlen($exception->getMessage())) { |
|
37
|
|
|
$message = $exception->getMessage(); |
|
38
|
|
|
} else { |
|
39
|
|
|
$message = 'Unknown server error.'; |
|
40
|
|
|
} |
|
41
|
|
|
$message = $this->errorMessages[get_class($exception)] ?? $message; |
|
42
|
|
|
|
|
43
|
|
|
$statusCode = $this->errorCodes[get_class($exception)] ?? 500; |
|
44
|
|
|
|
|
45
|
|
|
if (in_array('getStatusCode', get_class_methods($exception))) { |
|
46
|
|
|
$statusCode = $exception->getStatusCode(); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
if ($exception instanceof ValidationException) { |
|
50
|
|
|
$errors = collect($exception->errors())->flatten()->toArray(); |
|
51
|
|
|
$message = implode(PHP_EOL, $errors); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
return \response()->json([ |
|
55
|
|
|
'exception' => get_class($exception), |
|
56
|
|
|
'statusCode' => $statusCode, |
|
57
|
|
|
'message' => $message, |
|
58
|
|
|
], $statusCode); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|