繁体   English   中英

Swiftmailer异常未在Sy​​mfony2控制器中捕获

[英]Swiftmailer exception doesn't catch in Symfony2 controller

我正在开发一个以Gmail帐户为主机的简单邮件应用程序。它的工作原理很吸引人,但是当send()函数抛出异常时问题就出现了。 我看到try catch语句无法处理该异常。 即使使用Global异常类,它也不起作用。 这个问题也在某个地方讨论过。

例如 :

在Symfony2开发环境控制器中捕获swiftmailer异常

要么

https://groups.google.com/forum/#!topic/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对象时会处理异常?

当我评论此行时:

 $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 }的默认设置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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM