modules/InfonotModule/src/EventSubscriber/ExceptionSubscriber.php line 28

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace OnlineOcenka\InfonotModule\EventSubscriber;
  4. use OnlineOcenka\InfonotModule\Exception\RestApi\V2\ErrorValidationException;
  5. use Psr\Log\LoggerInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. class ExceptionSubscriber implements EventSubscriberInterface
  11. {
  12.     public function __construct(
  13.         private LoggerInterface $logger,
  14.     ) {
  15.     }
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [
  19.             KernelEvents::EXCEPTION => 'onKernelException',
  20.         ];
  21.     }
  22.     public function onKernelException(ExceptionEvent $event): void
  23.     {
  24.         $exception $event->getThrowable();
  25.         if(!$exception instanceof ErrorValidationException) {
  26.             return;
  27.         }
  28.         $data = [
  29.             'reason' => $exception->getMessage() ?: 'Произошла внутренняя ошибка'
  30.         ];
  31.         if($exception->errors) {
  32.             $data['errors'] = $exception->errors;
  33.         }
  34.         if($exception->getCode()) {
  35.             $data['code'] = $exception->getCode();
  36.         }
  37.         $event->setResponse(new JsonResponse($datastatus$exception->statusCode));
  38.         $this->logger->error($exception);
  39.         return;
  40.     }
  41. }