src/SupplierApiBundle/EventListener/ExceptionListener.php line 33

Open in your IDE?
  1. <?php
  2. namespace App\SupplierApiBundle\EventListener;
  3. use Symfony\Component\HttpFoundation\JsonResponse;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  6. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  7. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  8. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  9. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  10. class ExceptionListener
  11. {
  12.     /**
  13.      * @var string
  14.      */
  15.     private $host;
  16.     /**
  17.      * ExceptionListener constructor.
  18.      *
  19.      * @param string $host
  20.      */
  21.     public function __construct(string $host)
  22.     {
  23.         $this->host $host;
  24.     }
  25.     /**
  26.      * @param GetResponseForExceptionEvent $event
  27.      */
  28.     public function onKernelException(ExceptionEvent $event)
  29.     {
  30.         $request $event->getRequest();
  31.         if ($request->getHost() === $this->host) {
  32.             $response $this->createApiResponse($event->getThrowable());
  33.             $event->setResponse($response);
  34.         }
  35.     }
  36.     /**
  37.      * Creates the ApiResponse from any Exception
  38.      *
  39.      * @param \Exception $exception
  40.      *
  41.      * @return JsonResponse
  42.      */
  43.     private function createApiResponse(\Throwable $exception)
  44.     {
  45.         $statusCode $exception instanceof HttpExceptionInterface $exception->getStatusCode() : Response::HTTP_INTERNAL_SERVER_ERROR;
  46.         return new JsonResponse([
  47.             'code'    => $statusCode,
  48.             //'message' => $statusCode === 500 ? null : $this->getMessage( $exception )
  49.             'message'   => $this->getMessage($exception)
  50.         ], $statusCode);
  51.     }
  52.     private function getMessage(\Throwable $exception): string
  53.     {
  54.         if (! empty($exception->getMessage())) {
  55.             return $exception->getMessage();
  56.         }
  57.         if ($exception instanceof NotFoundHttpException) {
  58.             return 'Not found';
  59.         }
  60.         if ($exception instanceof AccessDeniedHttpException) {
  61.             return 'Access denied';
  62.         }
  63.         return 'Unknown error';
  64.     }
  65. }