【问题标题】:Symfony3: Centralized exception handlingSymfony3:集中式异常处理
【发布时间】:2016-08-03 04:38:51
【问题描述】:

我正在处理异常并尝试创建一个异常侦听器,其中将记录与数据库相关的异常并通过电子邮件发送。

但问题是当我捕获抛出的异常以向用户显示消息时未调用侦听器:

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
          }

          ...
          ...
       }
}

我想做的是在一个地方正确管理错误。谢谢。

【问题讨论】:

标签: php exception-handling symfony


【解决方案1】:

我实际上忽略了内核事件。当抛出异常时,HttpKernel 类会捕获它并调度kernel.exception 事件。 该事件仅在未捕获异常时发生

当出现未捕获的异常时发生 EXCEPTION 事件。

此事件允许您为抛出的异常创建响应或 修改抛出的异常。事件监听器方法接收一个 Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent 实例。

http://api.symfony.com/3.0/Symfony/Component/HttpKernel/KernelEvents.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-09
    相关资源
    最近更新 更多