src/Domain/Shared/Http/Listener/ExceptionListener.php line 26

Open in your IDE?
  1. <?php
  2. namespace App\Domain\Shared\Http\Listener;
  3. use App\Domain\Shared\Http\ApiResponse;
  4. use App\Domain\Shared\Http\Factory\NormalizerFactory;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  8. class ExceptionListener
  9. {
  10.     /**
  11.      * @var NormalizerFactory
  12.      */
  13.     private $normalizerFactory;
  14.     /**
  15.      * ExceptionListener constructor.
  16.      */
  17.     public function __construct(NormalizerFactory $normalizerFactory)
  18.     {
  19.         $this->normalizerFactory $normalizerFactory;
  20.     }
  21.     public function onKernelException(ExceptionEvent $event)
  22.     {
  23.         $exception $event->getThrowable();
  24.         $request $event->getRequest();
  25.         if (in_array('application/json'$request->getAcceptableContentTypes())) {
  26.             $response $this->createApiResponse($exception);
  27.             $event->setResponse($response);
  28.         }
  29.     }
  30.     /**
  31.      * Creates the ApiResponse from any Exception.
  32.      *
  33.      * @return ApiResponse
  34.      */
  35.     private function createApiResponse($exception)
  36.     {
  37.         $normalizer $this->normalizerFactory->getNormalizer($exception);
  38.         $statusCode $exception instanceof HttpExceptionInterface $exception->getStatusCode() : Response::HTTP_INTERNAL_SERVER_ERROR;
  39.         try {
  40.             $errors $normalizer $normalizer->normalize($exception) : [];
  41.         } catch (\Exception $e) {
  42.             $errors = [];
  43.         }
  44.         return new ApiResponse(true$exception->getMessage(),null$errors$statusCode);
  45.     }
  46. }