[英]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.