<?php
// src/EventSubscriber/ExceptionSubscriber.php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class ApiExceptionSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
// return the subscribed events, their methods and priorities
return [
KernelEvents::EXCEPTION => [
['processApiException', 10],
['logException', 0],
['notifyException', -10],
],
];
}
public function processApiException(ExceptionEvent $event)
{
$request = $event->getRequest();
$route = $request->getPathInfo();
$exception = $event->getThrowable();
if(str_starts_with($route, '/api/') && false === str_starts_with($route, '/api/doc') && $exception->getMessage()) {
$response = new JsonResponse([
'error' => $exception->getMessage(),
]);
$event->setResponse($response);
}
}
public function logException(ExceptionEvent $event)
{
// ...
}
public function notifyException(ExceptionEvent $event)
{
// ...
}
}