-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiExceptionRenderer.php
More file actions
73 lines (67 loc) · 2.67 KB
/
Copy pathApiExceptionRenderer.php
File metadata and controls
73 lines (67 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
declare(strict_types=1);
namespace App\Exceptions;
use App\Support\ApiResponse;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
/**
* Turns any exception thrown behind an API route into the standard error envelope.
*/
final class ApiExceptionRenderer
{
public function __invoke(Throwable $e, Request $request): ?JsonResponse
{
if (! $request->is('api/*')) {
return null;
}
return match (true) {
$e instanceof ValidationException => ApiResponse::error(
'The given data was invalid.',
Response::HTTP_UNPROCESSABLE_ENTITY,
$e->errors(),
),
$e instanceof AuthenticationException => ApiResponse::error(
$e->getMessage(),
Response::HTTP_UNAUTHORIZED,
),
$e instanceof AuthorizationException => ApiResponse::error(
'This action is unauthorized.',
Response::HTTP_FORBIDDEN,
),
$e instanceof ModelNotFoundException => ApiResponse::error(
'Resource not found.',
Response::HTTP_NOT_FOUND,
),
$e instanceof NotFoundHttpException => ApiResponse::error(
// Route model binding wraps a missing model in a 404 http exception.
$e->getPrevious() instanceof ModelNotFoundException ? 'Resource not found.' : 'Endpoint not found.',
Response::HTTP_NOT_FOUND,
),
$e instanceof MethodNotAllowedHttpException => ApiResponse::error(
'Method not allowed for this endpoint.',
Response::HTTP_METHOD_NOT_ALLOWED,
),
$e instanceof HttpExceptionInterface => ApiResponse::error(
$e->getMessage() !== '' ? $e->getMessage() : 'Request failed.',
$e->getStatusCode(),
),
default => $this->unexpected($e),
};
}
private function unexpected(Throwable $e): JsonResponse
{
return ApiResponse::error(
config('app.debug') ? $e->getMessage() : 'Something went wrong, please try again later.',
Response::HTTP_INTERNAL_SERVER_ERROR,
);
}
}