src/EventListener/ExceptionListener.php line 27

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Service\Api\Avanti\AvantiException;
  4. use App\Service\Log\LogService;
  5. use Neomerx\JsonApi\Encoder\Encoder;
  6. use Neomerx\JsonApi\Schema\Error;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpFoundation\JsonResponse;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. use Symfony\Component\HttpKernel\KernelInterface;
  13. class ExceptionListener implements EventSubscriberInterface
  14. {
  15.     private LogService $logService;
  16.     public function __construct(LogService $logServiceKernelInterface $kernel)
  17.     {
  18.         $this->logService $logService;
  19.         $this->env $kernel->getEnvironment();
  20.     }
  21.     public function onKernelException(ExceptionEvent $event): void
  22.     {
  23.         $exception $event->getThrowable();
  24.         $status Response::HTTP_BAD_REQUEST;
  25.         if ($exception->getCode() and array_key_exists($exception->getCode(), Response::$statusTexts)) {
  26.             $status $exception->getCode();
  27.         }
  28.         if (array_key_exists($statusResponse::$statusTexts)) {
  29.             $codeDesc Response::$statusTexts[$status];
  30.         } else {
  31.             $codeDesc preg_replace('#.*?\\\#is'''get_class($exception)); // just the class name, without the namespace
  32.         }
  33.         $trace $exception->getTrace();
  34.         if ($exception instanceof AvantiException) {
  35.             array_unshift($trace$exception->getAvantiError());
  36.         }
  37.         $this->logService->run([
  38.             'codeMessage' => $codeDesc,
  39.             'status'      => $status,
  40.             'message'     => $exception->getMessage(),
  41.             'file'        => $exception->getFile(),
  42.             'line'        => $exception->getLine(),
  43.             'trace'       => $exception->getTraceAsString(),
  44.             'avantiError' => $exception instanceof AvantiException $exception->getAvantiError() : null
  45.         ]);
  46.         $error = new Error(
  47.             null,
  48.             null,
  49.             null,
  50.             $status,
  51.             null,
  52.             $exception->getMessage(),
  53.             null,
  54.             $this->env === 'dev' $trace null,
  55.             false
  56.         );
  57.         $event->setResponse(new JsonResponse(json_decode(Encoder::instance()->encodeError($error)), $status));
  58.     }
  59.     /**
  60.      * @return mixed[]
  61.      */
  62.     public static function getSubscribedEvents()
  63.     {
  64.         return [
  65.             KernelEvents::EXCEPTION => 'onKernelException',
  66.         ];
  67.     }
  68. }