Créer la classe
La première chose à faire est de créer la classe Subscriber
qui va contenir la logique qu’on souhaite implanter :
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
class ApiProblemSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
}
}
Ensuite, compléter la méthode comme suit (c’est un exemple) :
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
class ApiProblemSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return array(
KernelEvents::EXCEPTION => 'onKernelException'
);
}
}
Pour connaître les autres évènements, et surtout le type d’évènement reçu, il suffit de jeter un oeil dans la classe Symfony\Component\HttpKernel\KernelEvents
. Dans notre cas, il s’agit de GetResponseForExceptionEvent
:
namespace Symfony\Component\HttpKernel;
final class KernelEvents
{
//--
/**
* The EXCEPTION event occurs when an uncaught exception appears.
*
* This event allows you to create a response for a thrown exception or
* to modify the thrown exception.
*
* @Event("Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent")
*/
const EXCEPTION = 'kernel.exception';
}
Exemple complet
Pour finir, on peut maintenant compléter notre Subscriber
puisque nous savons quel type d’évènement on va recevoir dans le callback :
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
class ApiProblemSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return array(
KernelEvents::EXCEPTION => 'onKernelException'
);
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
// --
}
}
A noter que tout ceci fonctionne à condition d’avoir l’autoconfigure
à true
:
# config/services.yaml
services:
# default configuration for services in *this* file
_defaults:
autowire: true
autoconfigure: true
Commentaires récents