96 lines
2.5 KiB
PHP
96 lines
2.5 KiB
PHP
<?php
|
|
/** @noinspection PhpUndefinedClassInspection */
|
|
|
|
|
|
namespace TorstenHettstedt\TimekeepingApi\Middleware;
|
|
|
|
|
|
use JetBrains\PhpStorm\ArrayShape;
|
|
use Psr\Container\ContainerInterface;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Psr\Http\Message\ServerRequestInterface;
|
|
use Psr\Log\LoggerInterface;
|
|
use Slim\App;
|
|
use Slim\Exception\HttpException;
|
|
use Throwable;
|
|
|
|
class ErrorHandler
|
|
{
|
|
/**
|
|
* @var App<ContainerInterface>
|
|
*/
|
|
protected App $app;
|
|
|
|
/**
|
|
* ErrorHandler constructor.
|
|
*
|
|
* @param App<ContainerInterface> $app
|
|
*/
|
|
public function __construct(App $app)
|
|
{
|
|
$this->app = $app;
|
|
}
|
|
|
|
/**
|
|
* @param Throwable $exception
|
|
*
|
|
* @return array<string, mixed>
|
|
*/
|
|
#[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);
|
|
}
|
|
|
|
} |