<?php
declare(strict_types=1);
namespace App\EventListener\Api;
use App\Service\EnvironmentService;
use Sentry\State\Scope;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use function Sentry\captureException;
class ApiExceptionListener
{
protected EnvironmentService $environmentService;
public function __construct(EnvironmentService $environmentService)
{
$this->environmentService = $environmentService;
}
public function onKernelException(ExceptionEvent $event): void
{
if (!$this->environmentService->isApi()) {
return;
}
if (!$event->getThrowable() instanceof HttpException) {
\Sentry\configureScope(
function (Scope $scope): void {
$scope->setTag('origin', 'customer_error_response');
}
);
$eventId = captureException($event->getThrowable());
$event->setResponse(
new JsonResponse(
[
'code' => Response::HTTP_INTERNAL_SERVER_ERROR,
'message' => 'An error has occurred. Please try again later. The team has been notify with case id: '.$eventId,
],
Response::HTTP_INTERNAL_SERVER_ERROR
)
);
return;
}
$event->setResponse(
new JsonResponse(
[
'code' => Response::HTTP_BAD_REQUEST,
'message' => 'Bad request',
],
Response::HTTP_BAD_REQUEST
)
);
}
}