*/ protected App $app; /** * ErrorHandler constructor. * * @param App $app */ public function __construct(App $app) { $this->app = $app; } /** * @param Throwable $exception * * @return array */ #[ArrayShape([ 'timestamp' => "false|string", 'status' => "int", "error" => "string", 'message' => "string", 'path' => "string" ])] protected function buildJsonArray(Throwable $exception): array { $payload = [ 'timestamp' => date('Y-m-d\TH:m:sP'), 'status' => $exception->getCode(), "error" => '', 'message' => $exception->getMessage(), 'path' => $exception->getFile() ]; if ($exception instanceof HttpException) { $payload['error'] = $exception->getTitle(); } return $payload; } /** * @param ServerRequestInterface $request * @param Throwable $exception * @param bool $displayErrorDetails * @param bool $logErrors * @param bool $logErrorDetails * @param LoggerInterface|null $logger * * @return ResponseInterface */ public function __invoke( ServerRequestInterface $request, Throwable $exception, bool $displayErrorDetails, bool $logErrors, bool $logErrorDetails, ?LoggerInterface $logger = null ): ResponseInterface { if ($logger !== null && $logErrors === true) { $logger->error($exception->getMessage()); } $payload = $this->buildJsonArray($exception); $response = $this->app->getResponseFactory()->createResponse($exception->getCode()); $response->getBody()->write( json_encode($payload, JSON_UNESCAPED_UNICODE) ); $originAccessControlHandler = new OriginAccessControlHandler(); return $originAccessControlHandler->originAccessControl($request, $response); } }