src/EventListener/ApiExceptionListener.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpFoundation\JsonResponse;
  4. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  5. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  6. use Symfony\Component\HttpKernel\KernelInterface;
  7. class ApiExceptionListener
  8. {
  9.     private bool $debug;
  10.     public function __construct(KernelInterface $kernel)
  11.     {
  12.         $this->debug $kernel->isDebug();
  13.     }
  14.     public function onKernelException(ExceptionEvent $event): void
  15.     {
  16.         // if debug, symfony handles it
  17.         if ($this->debug) {
  18.             return;
  19.         }
  20.         $request $event->getRequest();
  21.         // only for api requests
  22.         if (
  23.             $request->getRequestFormat() !== 'json' &&
  24.             !str_starts_with($request->getPathInfo(), '/api')
  25.         ) {
  26.             return;
  27.         }
  28.         $exception $event->getThrowable();
  29.         $status $exception instanceof HttpExceptionInterface
  30.             $exception->getStatusCode()
  31.             : 500;
  32.         $responseData = [
  33.             'title' => 'An error occurred',
  34.             'status' => $statusCode,
  35.             'detail' => $exception->getMessage(),
  36.             'class' => get_class($exception),
  37.         ];
  38.         $event->setResponse(new JsonResponse($responseData$status));
  39.     }
  40. }