src/Listeners/BadRequestListener.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Listeners;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\{JsonResponseResponse};
  5. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. class BadRequestListener implements EventSubscriberInterface
  9. {
  10.     public function onKernelException(ExceptionEvent $event)
  11.     {
  12.         $exception $event->getThrowable();
  13.         if ($exception instanceof BadRequestHttpException) {
  14.             $event->allowCustomResponseCode();
  15.             $response = new JsonResponse(
  16.                 [
  17.                     'result' => false,
  18.                     'message' => $exception->getMessage()
  19.                 ],
  20.                 Response::HTTP_BAD_REQUEST
  21.             );
  22.             $event->setResponse($response);
  23.         }
  24.     }
  25.     public static function getSubscribedEvents(): array
  26.     {
  27.         return [
  28.             KernelEvents::EXCEPTION => [
  29.                 ['onKernelException'64]
  30.             ]
  31.         ];
  32.     }
  33. }