Swiftmailer异常不会';t在Symfony2控制器中捕获


Swiftmailer exception doesn't catch in Symfony2 controller

我正在开发一个以Gmail帐户为主机的简单邮件应用程序。它的工作原理就像一个魅力,但当send()函数抛出异常时,问题就会出现。我发现try-catch语句无法处理异常。即使我使用全局异常类,它也不起作用。这个问题也在某个地方讨论过。

例如:

在Symfony2 dev-env控制器中捕获swiftmailer异常

https://groups.google.com/forum/#!主题/symfony2/SlEzg_PKwJw

但他们没有找到一个有效的答案。

我的控制器功能代码是:

    public function ajaxRegisterPublisherAction()
    {
//some irrelevant logic
     $returns=  json_encode(array("username"=>$username,"responseCode"=>$responseCode));

    try{
            $message = 'Swift_Message::newInstance()
        ->setSubject('hello world')
        ->setFrom('jafarzadeh91@gmail.com')
        ->setTo('jafarzadeh991@yahoo.com')
        ->setBody(
            $this->renderView('AcmeSinamelkBundle:Default:email.txt.twig',array('name'=>$username,"password"=>$password))
        );
      $this->container->get("mailer")->send($message);
    }
   catch (Exception $e)
    {
    }

    return new 'Symfony'Component'HttpFoundation'Response($returns,200,array('Content-Type'=>'application/json'));

    }

我在firebug控制台中收到的来自上述代码的响应是:

{"username":"xzdvxvvcvxcv","responseCode":200}<!DOCTYPE html>
<html>
    .
    .
Swift_TransportException: Connection could not be established with host smtp.gmail.com [Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?]
    .
    .
</html>

我抓头发是因为我不知道为什么内核会在我的json对象的continue中处理异常?

当我评论这句话时:

 $this->container->get("mailer")->send($message);

异常不会发生,并且我在客户端有一个有效的json。(当然了)我将Exception更改为'Exception'Swift_TransportException,甚至Swift_TransportException!但是没有好的结果。

执行$this->container->get("mailer")->send($message);时,如果已打开后台处理,则此时不会发送电子邮件。请参阅http://symfony.com/doc/current/cookbook/email/spool.html

如果您有spool: { type: memory }的默认设置,那么在控制器退出后,'Swift_TransportException将在内核终止阶段抛出。解决这一问题的一种方法是关闭后台处理(但在发送电子邮件时,用户可能需要等待),或者您可以创建自己的事件侦听器来处理异常。http://symfony.com/doc/current/cookbook/service_container/event_listener.html

在事件调度程序发回异常之前,您需要击败它,所以请倾听此类事件并使其静音,尽管我认为这是一种糟糕的处理方法

class SuchABadRequest implements 'Swift_Events_TransportExceptionListener{
    /**
     * Invoked as a TransportException is thrown in the Transport system.
     *
     * @param 'Swift_Events_TransportExceptionEvent $evt
     */
    public function exceptionThrown('Swift_Events_TransportExceptionEvent $evt)
    {
        $evt->cancelBubble();
        try{
            throw $evt->getException();
        }catch('Swift_TransportException $e){
            print_r($e->getMessage());
        }
    }
}

控制器内部

$mailer = $this->get('mailer');
$mailer->registerPlugin(new SuchABadRequest());