Reputation: 111
I'm working on exceptions and trying to create an exception listener wherein the exceptions related to database will be logged and emailed.
But the problem is that the listener is not called when I catch the thrown exception to show a message to the user as:
try {
try {
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('AppBundle:User')
->getUserByEmail('[email protected]');
}
catch(\Doctrine\DBAL\DBALException $e) {
throw new \Doctrine\DBAL\DBALException('DBAL error!!');
}
}
catch(\Exception $e) {
echo $e->getMessage();
}
The same listener is called when the error is not rendered:
try {
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('AppBundle:User')
->getUserByEmail('[email protected]');
}
catch(\Doctrine\DBAL\DBALException $e) {
throw new \Doctrine\DBAL\DBALException('DBAL error!!');
}
The exception listener:
class ExceptionListener {
public function onKernelException(GetResponseForExceptionEvent $event) {
$exception = $event->getException();
if ($exception instance of \Doctrine\DBAL\DBALException) {
//log the error
}
...
...
}
}
What I want to do is manage the errors properly and at one place. Thanks.
Upvotes: 3
Views: 840
Reputation: 111
I actually overlooked the Kernel events. When an exception is thrown, the HttpKernel class catches it and dispatches a kernel.exception
event. The event only occurs when an exception is left uncaught.
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. The event listener method receives a Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent instance.
http://api.symfony.com/3.0/Symfony/Component/HttpKernel/KernelEvents.html
Upvotes: 1