src/EventListener/Api/ApiExceptionListener.php line 25

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventListener\Api;
  4. use App\Service\EnvironmentService;
  5. use Sentry\State\Scope;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  9. use Symfony\Component\HttpKernel\Exception\HttpException;
  10. use function Sentry\captureException;
  11. class ApiExceptionListener
  12. {
  13.     protected EnvironmentService $environmentService;
  14.     public function __construct(EnvironmentService $environmentService)
  15.     {
  16.         $this->environmentService $environmentService;
  17.     }
  18.     public function onKernelException(ExceptionEvent $event): void
  19.     {
  20.         if (!$this->environmentService->isApi()) {
  21.             return;
  22.         }
  23.         if (!$event->getThrowable() instanceof HttpException) {
  24.             \Sentry\configureScope(
  25.                 function (Scope $scope): void {
  26.                     $scope->setTag('origin''customer_error_response');
  27.                 }
  28.             );
  29.             $eventId captureException($event->getThrowable());
  30.             $event->setResponse(
  31.                 new JsonResponse(
  32.                     [
  33.                         'code' => Response::HTTP_INTERNAL_SERVER_ERROR,
  34.                         'message' => 'An error has occurred. Please try again later. The team has been notify with case id: '.$eventId,
  35.                     ],
  36.                     Response::HTTP_INTERNAL_SERVER_ERROR
  37.                 )
  38.             );
  39.             return;
  40.         }
  41.         $event->setResponse(
  42.             new JsonResponse(
  43.                 [
  44.                     'code' => Response::HTTP_BAD_REQUEST,
  45.                     'message' => 'Bad request',
  46.                 ],
  47.                 Response::HTTP_BAD_REQUEST
  48.             )
  49.         );
  50.     }
  51. }