src/Api/EventListener/ExceptionListener.php line 32

Open in your IDE?
  1. <?php
  2. namespace Api\EventListener;
  3. use App\Entity\Central\Client\Client;
  4. use App\Entity\Client\PointOfSale\PointOfSale;
  5. use App\Entity\Client\Store\Store;
  6. use App\Service\AppManager;
  7. use Psr\Log\LoggerInterface;
  8. use Symfony\Component\HttpFoundation\JsonResponse;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  11. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  12. use Symfony\Component\HttpKernel\KernelInterface;
  13. class ExceptionListener
  14. {
  15.     private $kernel;
  16.     private $logger;
  17.     private $appManager;
  18.     public function __construct(KernelInterface $kernelLoggerInterface $loggerAppManager $appManager)
  19.     {
  20.         $this->appManager $appManager;
  21.         $this->kernel $kernel;
  22.         $this->logger $logger;
  23.     }
  24.     /**
  25.      * @param ExceptionEvent $event
  26.      */
  27.     public function onKernelException(ExceptionEvent $event)
  28.     {
  29.         $exception $event->getThrowable();
  30.         $response $this->createApiResponse($exception);
  31.         if ($response instanceof JsonResponse){
  32.             $event->setResponse($response);
  33.         }
  34.     }
  35.     /**
  36.      * @param \Throwable $throwable
  37.      * @return JsonResponse
  38.      */
  39.     private function createApiResponse(\Throwable $throwable)
  40.     {
  41.         $statusCode $throwable instanceof HttpExceptionInterface $throwable->getStatusCode() : Response::HTTP_INTERNAL_SERVER_ERROR;
  42.         $data = ['error' => !$throwable instanceof HttpExceptionInterface && !$this->kernel->isDebug() ? 'Internal server error' $throwable->getMessage()];
  43.         if ($this->kernel->isDebug()){
  44.             $data['backtrace'] = $throwable->getTrace();
  45.         }
  46.         if ($statusCode === 500){
  47.             $context = ['exception' => $throwable->getTraceAsString()];
  48.             if ($this->appManager->getClient() instanceof Client){
  49.                 $context['client'] = $this->appManager->getClient()->__toString();
  50.             }
  51.             if ($this->appManager->getStore() instanceof Store){
  52.                 $context['store'] = $this->appManager->getStore()->__toString();
  53.             }
  54.             if ($this->appManager->getPointOfSale() instanceof PointOfSale){
  55.                 $context['point_of_sale'] = $this->appManager->getPointOfSale()->getName();
  56.             }
  57.             $this->logger->critical($throwable->getMessage(), $context);
  58.         }
  59.         return new JsonResponse(json_encode($data), $statusCode, [], true);
  60.     }
  61. }