local/modules/OpenApi/EventListener/ExceptionListener.php line 58

  1. <?php
  2. namespace OpenApi\EventListener;
  3. use OpenApi\Exception\OpenApiException;
  4. use OpenApi\Model\Api\Error;
  5. use OpenApi\Model\Api\ModelFactory;
  6. use OpenApi\OpenApi;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. use Thelia\Core\HttpFoundation\JsonResponse;
  11. use Thelia\Core\Translation\Translator;
  12. use Thelia\Log\Tlog;
  13. class ExceptionListener implements EventSubscriberInterface
  14. {
  15.     /** @var ModelFactory */
  16.     protected $modelFactory;
  17.     public function __construct(ModelFactory $modelFactory)
  18.     {
  19.         $this->modelFactory $modelFactory;
  20.     }
  21.     /**
  22.      * Convert all exception to OpenApiException if route is an open api route.
  23.      */
  24.     public function catchAllException(ExceptionEvent $event): void
  25.     {
  26.         // Do nothing if this is already an Open Api Exception
  27.         if ($event->getThrowable() instanceof OpenApiException) {
  28.             return;
  29.         }
  30.         // Do nothing on non-api routes
  31.         if (!$event->getRequest()->attributes->get(OpenApi::OPEN_API_ROUTE_REQUEST_KEYfalse)) {
  32.             return;
  33.         }
  34.         Tlog::getInstance()->error($event->getThrowable()->getTraceAsString());
  35.         /** @var Error $error */
  36.         $error $this->modelFactory->buildModel(
  37.             'Error',
  38.             [
  39.                 'title' => Translator::getInstance()->trans('Unexpected error', [], OpenApi::DOMAIN_NAME),
  40.                 'description' => $event->getThrowable()->getMessage(),
  41.             ]
  42.         );
  43.         $event->setThrowable((new OpenApiException($error)));
  44.     }
  45.     /**
  46.      * Format OpenApiException to JSON response.
  47.      */
  48.     public function catchOpenApiException(ExceptionEvent $event): void
  49.     {
  50.         if (!$event->getThrowable() instanceof OpenApiException) {
  51.             return;
  52.         }
  53.         /** @var OpenApiException $openApiException */
  54.         $openApiException $event->getThrowable();
  55.         $response = new JsonResponse($openApiException->getError(), $openApiException->getHttpCode());
  56.         $event->setResponse($response);
  57.     }
  58.     public static function getSubscribedEvents()
  59.     {
  60.         return [
  61.             KernelEvents::EXCEPTION => [
  62.                 ['catchOpenApiException'256],
  63.                 ['catchAllException'512],
  64.             ],
  65.         ];
  66.     }
  67. }