src/EventListener/ExceptionListener.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpFoundation\JsonResponse;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  6. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  7. class ExceptionListener
  8. {
  9.     public const HEADERS = ['Content-Type' => 'application/problem+json; charset=utf-8'];
  10.     public function onKernelException(ExceptionEvent $event): void
  11.     {
  12.         if ('prod' === getenv('APP_ENV')) {
  13.             $exception $event->getThrowable();
  14.             switch ($exception) {
  15.                 case $exception instanceof NotFoundHttpException:
  16.                     $this->handleNotFoundHttpException($event);
  17.                     break;
  18.                 default:
  19.                     $this->handleDefaultException($event);
  20.                     break;
  21.             }
  22.         }
  23.     }
  24.     private function handleNotFoundHttpException(ExceptionEvent $event): void
  25.     {
  26.         $event->setResponse(
  27.             new JsonResponse(
  28.                 $this->getFormatedError($event->getThrowable()->getMessage()),
  29.                 Response::HTTP_NOT_FOUND,
  30.                 self::HEADERS
  31.             )
  32.         );
  33.     }
  34.     private function handleDefaultException(ExceptionEvent $event): void
  35.     {
  36.         $appDebug getenv('APP_DEBUG');
  37.         if (!$appDebug) {
  38.             $event->setResponse(
  39.                 new JsonResponse(
  40.                     $this->getFormatedError('An error occurred. please try again or contact the administrator'),
  41.                     Response::HTTP_INTERNAL_SERVER_ERROR,
  42.                     self::HEADERS
  43.                 )
  44.             );
  45.         }
  46.     }
  47.     private function getFormatedError(string $message): array
  48.     {
  49.         return [
  50.             'title' => 'Validation Failed',
  51.             'detail' => str_replace('"'"'"$message),
  52.         ];
  53.     }
  54. }