src/Listener/JsonExceptionResponseTransformerListener.php line 14

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Listener;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  6. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  7. class JsonExceptionResponseTransformerListener
  8. {
  9.     public function onKernelException(ExceptionEvent $event): void
  10.     {
  11.         $exception $event->getThrowable();
  12.         if ($exception instanceof HttpExceptionInterface) {
  13.             $data = [
  14.                 'class' => \get_class($exception),
  15.                 'code' => $exception->getStatusCode(),
  16.                 'message' => $exception->getMessage(),
  17.             ];
  18.             $response $this->prepareResponse($data$data['code']);
  19.             $event->setResponse($response);
  20.         }
  21.     }
  22.     private function prepareResponse(array $dataint $statusCode): JsonResponse
  23.     {
  24.         $response = new JsonResponse($data$statusCode);
  25.         $response->headers->set('Server-Time', \time());
  26.         $response->headers->set('X-Error-Code'$statusCode);
  27.         return $response;
  28.     }
  29. }