|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace App\Http; |
| 6 | + |
| 7 | +use Psr\Http\Message\ResponseFactoryInterface; |
| 8 | +use Psr\Http\Message\ResponseInterface; |
| 9 | +use Throwable; |
| 10 | +use Yiisoft\ErrorHandler\Exception\UserException; |
| 11 | +use Yiisoft\ErrorHandler\Middleware\ExceptionResponder; |
| 12 | +use Yiisoft\Injector\Injector; |
| 13 | +use Yiisoft\Input\Http\InputValidationException; |
| 14 | + |
| 15 | +final readonly class ExceptionResponderFactory |
| 16 | +{ |
| 17 | + public function __construct( |
| 18 | + private ResponseFactoryInterface $responseFactory, |
| 19 | + private ApiResponseFactory $apiResponseFactory, |
| 20 | + private Injector $injector, |
| 21 | + ) {} |
| 22 | + |
| 23 | + public function create(): ExceptionResponder |
| 24 | + { |
| 25 | + return new ExceptionResponder( |
| 26 | + [ |
| 27 | + InputValidationException::class => $this->inputValidationException(...), |
| 28 | + Throwable::class => $this->throwable(...), |
| 29 | + ], |
| 30 | + $this->responseFactory, |
| 31 | + $this->injector, |
| 32 | + ); |
| 33 | + } |
| 34 | + |
| 35 | + private function inputValidationException(InputValidationException $exception): ResponseInterface |
| 36 | + { |
| 37 | + return $this->apiResponseFactory->failValidation($exception->getResult()); |
| 38 | + } |
| 39 | + |
| 40 | + private function throwable(Throwable $exception): ResponseInterface |
| 41 | + { |
| 42 | + if (UserException::isUserException($exception)) { |
| 43 | + $code = $exception->getCode(); |
| 44 | + return $this->apiResponseFactory->fail( |
| 45 | + $exception->getMessage(), |
| 46 | + code: is_int($code) ? $code : null, |
| 47 | + ); |
| 48 | + } |
| 49 | + throw $exception; |
| 50 | + } |
| 51 | +} |
0 commit comments