diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/Http/Exceptions/HttpException.php | 51 | ||||
-rw-r--r-- | src/Middleware/ErrorHandler.php | 21 |
2 files changed, 71 insertions, 1 deletions
diff --git a/src/Http/Exceptions/HttpException.php b/src/Http/Exceptions/HttpException.php new file mode 100644 index 00000000..07853d1e --- /dev/null +++ b/src/Http/Exceptions/HttpException.php @@ -0,0 +1,51 @@ +<?php + +namespace Engelsystem\Http\Exceptions; + +use RuntimeException; +use Throwable; + +class HttpException extends RuntimeException +{ + /** @var int */ + protected $statusCode; + + /** @var array */ + protected $headers = []; + + /** + * @param int $statusCode + * @param string $message + * @param array $headers + * @param int $code + * @param Throwable|null $previous + */ + public function __construct( + int $statusCode, + string $message = '', + array $headers = [], + int $code = 0, + Throwable $previous = null + ) { + $this->headers = $headers; + $this->statusCode = $statusCode; + + parent::__construct($message, $code, $previous); + } + + /** + * @return array + */ + public function getHeaders(): array + { + return $this->headers; + } + + /** + * @return int + */ + public function getStatusCode(): int + { + return $this->statusCode; + } +}
\ No newline at end of file diff --git a/src/Middleware/ErrorHandler.php b/src/Middleware/ErrorHandler.php index a7c4cfe6..c99ac24f 100644 --- a/src/Middleware/ErrorHandler.php +++ b/src/Middleware/ErrorHandler.php @@ -2,6 +2,7 @@ namespace Engelsystem\Middleware; +use Engelsystem\Http\Exceptions\HttpException; use Engelsystem\Http\Response; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; @@ -38,7 +39,11 @@ class ErrorHandler implements MiddlewareInterface ServerRequestInterface $request, RequestHandlerInterface $handler ): ResponseInterface { - $response = $handler->handle($request); + try { + $response = $handler->handle($request); + } catch (HttpException $e) { + $response = $this->createResponse($e->getMessage(), $e->getStatusCode(), $e->getHeaders()); + } $statusCode = $response->getStatusCode(); if ($statusCode < 400 || !$response instanceof Response) { @@ -77,4 +82,18 @@ class ErrorHandler implements MiddlewareInterface return 'default'; } + + /** + * Create a new response + * + * @param string $content + * @param int $status + * @param array $headers + * @return Response + * @codeCoverageIgnore + */ + protected function createResponse(string $content = '', int $status = 200, array $headers = []) + { + return response($content, $status, $headers); + } } |