我正在处理异常,并试图创建一个异常侦听器,其中与数据库相关的异常将被记录并通过电子邮件发送。
但问题是,当我捕捉到抛出的异常并将消息显示给用户时,侦听器不会被调用为:
try {
try {
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('AppBundle:User')
->getUserByEmail('abc@example.com');
}
catch('Doctrine'DBAL'DBALException $e) {
throw new 'Doctrine'DBAL'DBALException('DBAL error!!');
}
}
catch('Exception $e) {
echo $e->getMessage();
}
未呈现错误时调用相同的侦听器:
try {
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('AppBundle:User')
->getUserByEmail('abc@example.com');
}
catch('Doctrine'DBAL'DBALException $e) {
throw new 'Doctrine'DBAL'DBALException('DBAL error!!');
}
异常侦听器:
class ExceptionListener {
public function onKernelException(GetResponseForExceptionEvent $event) {
$exception = $event->getException();
if ($exception instance of 'Doctrine'DBAL'DBALException) {
//log the error
}
...
...
}
}
我想做的是在一个地方正确地管理错误。谢谢
我实际上忽略了内核事件。当抛出异常时,HttpKernel类会捕获它并分派一个kernel.exception
事件只有在未捕获异常的情况下才会发生该事件。
当出现未捕获的异常时,会发生EXCEPTION事件。
此事件允许您为抛出的异常或以修改引发的异常。事件侦听器方法接收Symfony''Component''HttpKernel''Event''GetResponseForExceptionEvent例子
http://api.symfony.com/3.0/Symfony/Component/HttpKernel/KernelEvents.html