|
11 | 11 | use Tempest\Http\GenericResponse; |
12 | 12 | use Tempest\Http\HttpRequestFailed; |
13 | 13 | use Tempest\Http\Response; |
| 14 | +use Tempest\Http\Responses\Json; |
14 | 15 | use Tempest\Http\Session\CsrfTokenDidNotMatch; |
15 | 16 | use Tempest\Http\Status; |
16 | 17 | use Tempest\Router\ResponseSender; |
17 | 18 | use Tempest\Support\Filesystem; |
18 | 19 | use Tempest\View\GenericView; |
19 | 20 | use Throwable; |
20 | 21 |
|
| 22 | +use function Tempest\Support\arr; |
| 23 | + |
21 | 24 | final readonly class HttpExceptionHandler implements ExceptionHandler |
22 | 25 | { |
23 | 26 | public function __construct( |
@@ -49,6 +52,30 @@ public function handle(Throwable $throwable): void |
49 | 52 |
|
50 | 53 | private function renderErrorResponse(Status $status, ?HttpRequestFailed $exception = null): Response |
51 | 54 | { |
| 55 | + if ($exception->request->headers->get('Accept') === 'application/json') { |
| 56 | + return new Json( |
| 57 | + $this->appConfig->environment->isLocal() && $exception !== null |
| 58 | + ? [ |
| 59 | + 'message' => $exception->getMessage(), |
| 60 | + 'exception' => get_class($exception), |
| 61 | + 'file' => $exception->getFile(), |
| 62 | + 'line' => $exception->getLine(), |
| 63 | + 'trace' => arr($exception->getTrace())->map( |
| 64 | + fn ($trace) => arr($trace)->removeKeys('args')->toArray(), |
| 65 | + )->toArray(), |
| 66 | + ] : [ |
| 67 | + 'message' => $exception?->getMessage() ?: match ($status) { |
| 68 | + Status::INTERNAL_SERVER_ERROR => 'An unexpected server error occurred', |
| 69 | + Status::NOT_FOUND => 'This page could not be found on the server', |
| 70 | + Status::FORBIDDEN => 'You do not have permission to access this page', |
| 71 | + Status::UNAUTHORIZED => 'You must be authenticated in to access this page', |
| 72 | + Status::UNPROCESSABLE_CONTENT => 'The request could not be processed due to invalid data', |
| 73 | + default => null, |
| 74 | + }, |
| 75 | + ], |
| 76 | + )->setStatus($status); |
| 77 | + } |
| 78 | + |
52 | 79 | return new GenericResponse( |
53 | 80 | status: $status, |
54 | 81 | body: new GenericView(__DIR__ . '/HttpErrorResponse/error.view.php', [ |
|
0 commit comments