src/EventSubscriber/ExceptionSubscriber.php line 37
<?phpnamespace App\EventSubscriber;use App\Factory\JsonResponseInterface;use App\Normalizer\ExceptionNormalizerFormatterInterface;use App\Normalizer\NormalizerInterface;use Symfony\Component\EventDispatcher\EventSubscriberInterface;use Symfony\Component\HttpKernel\Event\ExceptionEvent;use Symfony\Component\HttpKernel\KernelEvents;use Symfony\Component\Serializer\SerializerInterface;/*** @author Roméo Razafindrakoto <romeorazaf@myagency.mg>*/class ExceptionSubscriber implements EventSubscriberInterface{/*** @var array<NormalizerInterface>*/private static array $normalizers;public function __construct(private readonly SerializerInterface $serializer,private readonly ExceptionNormalizerFormatterInterface $exceptionNormalizerFormatter,private readonly JsonResponseInterface $jsonResponse) {}public static function getSubscribedEvents(): array{return [KernelEvents::EXCEPTION => [['processException', 0]],];}public function processException(ExceptionEvent $event): void{$result = null;$request = $event->getRequest();$exception = $event->getThrowable();if (str_contains($request->getRequestUri(), '/api')) {foreach (self::$normalizers as $key => $normalizer) {if ($normalizer->supports($exception)) {$result = $normalizer->normalize($exception);break;}}if (null === $result) {$result = $this->exceptionNormalizerFormatter->format($exception->getMessage());}$event->setResponse($this->jsonResponse->getJsonResponse(intval($result['code']),$this->serializer->serialize($result, 'json')));}}public function addNormalizer(NormalizerInterface $normalizer): void{self::$normalizers[] = $normalizer;}}