Cod*_*ork 8 php swiftmailer symfony
我正在使用Gmail帐户作为主机开发一个简单的邮件应用程序.它就像一个魅力,但当send()函数抛出异常时问题就出现了.我看到try catch语句无法处理异常.即使我使用Global异常类,它也不起作用.在某个地方也讨论过这个问题.
例如 :
在Symfony2 dev env控制器中捕获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'));
}
Run Code Online (Sandbox Code Playgroud)
我在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>
Run Code Online (Sandbox Code Playgroud)
我抓住了我的头发,因为我不知道为什么内核在继续我的json对象时处理异常?
当我评论这一行时:
$this->container->get("mailer")->send($message);
Run Code Online (Sandbox Code Playgroud)
异常不会发生,我有一个有效的JSON在客户端(即尽管此事-OF-当然)我换Exception到\Exception或者\Swift_TransportException甚至Swift_TransportException!但没有好结果.
你需要在事件调度程序发送回异常之前击败它,所以监听这些类型的事件并让它们静音,尽管我认为这是一个糟糕的处理方式
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
控制器内部
$mailer = $this->get('mailer');
$mailer->registerPlugin(new SuchABadRequest());
Run Code Online (Sandbox Code Playgroud)