src/EventSubscriber/PartnerApi/PartnerApiExceptionSubscriber.php line 22

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\PartnerApi;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\HttpKernel\Exception\HttpException;
  8. use Symfony\Component\HttpKernel\KernelInterface;
  9. class PartnerApiExceptionSubscriber implements EventSubscriberInterface
  10. {
  11.     public function __construct(
  12.         private KernelInterface $kernel,
  13.         private string $partnerApiPath,
  14.     )
  15.     {
  16.     }
  17.     public function onKernelException(ExceptionEvent $event): void
  18.     {
  19.         if ($this->kernel->getEnvironment() === 'dev') {
  20.             return;
  21.         }
  22.         if (!str_starts_with($event->getRequest()->getPathInfo(), "/$this->partnerApiPath")) {
  23.             return;
  24.         }
  25.         $exception $event->getThrowable();
  26.         $status $exception instanceof HttpException $exception->getStatusCode() : Response::HTTP_INTERNAL_SERVER_ERROR;
  27.         $event->setResponse(new JsonResponse([
  28.             'status'  => $status,
  29.             'message' => $exception->getMessage(),
  30.         ], $status));
  31.     }
  32.     public static function getSubscribedEvents(): array
  33.     {
  34.         return [
  35.             'kernel.exception' => 'onKernelException',
  36.         ];
  37.     }
  38. }