src/EventListener/ExceptionListener.php line 26

Open in your IDE?
  1. <?php
  2. /*
  3.  *  This file is part of the cargo app.
  4.  *
  5.  *  Copyright 2024 logist.cloud <support@logist.cloud>
  6.  */
  7. namespace App\EventListener;
  8. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  9. use Symfony\Component\DependencyInjection\Attribute\Autowire;
  10. use Symfony\Component\HttpFoundation\AcceptHeader;
  11. use Symfony\Component\HttpFoundation\JsonResponse;
  12. use App\Exception\LogistProdException;
  13. /**
  14.  * @author Grigoriy Kulin <yarboroda@gmail.com>
  15.  */
  16. class ExceptionListener
  17. {
  18.     public function __construct(#[Autowire(value'%kernel.environment%')] private string $env
  19.     {
  20.     }
  21.     
  22.     public function __invoke(ExceptionEvent $event): void
  23.     {
  24.         $exception $event->getThrowable();
  25.         $request $event->getRequest();
  26.         $accept AcceptHeader::fromString($request->headers->get('Accept'));
  27.         if(!$accept->has('application/json') || !$exception instanceof \JsonSerializable){
  28.             return;
  29.         }
  30.         $code $exception->getCode();
  31.         if($this->env !== 'dev' && $this->env !== 'test'){
  32.             $exception = new LogistProdException('exception proxy for prod'$code$exception);
  33.         }
  34.         $response = new JsonResponse($exception$code, ['Content-Type' => $request->getMimeType('application/json')]);
  35.         $event->setResponse($response);
  36.     }
  37. }