2012-07-15 114 views
10

我不知道爲什麼我沒有從我的控制器中捕獲Swiftmailer的異常。我做錯了什麼,或失蹤?在Symfony2開發環境控制器中捕獲swiftmailer異常

在控制器我有:

try { 
    $this->get('mailer')->send($email); 
} 
catch (\Swift_TransportException $e) { 
    $result = array(
     false, 
     'There was a problem sending email: ' . $e->getMessage() 
    ); 
} 

看來它得到我的代碼之前得到通過的Symfony抓住,這樣反而能夠處理的錯誤我自己,我有 Swift_TransportException: Connection could not be established得到標準的500頁

如果電子郵件無法發送,那麼由於電子郵件並不重要,應用程序無需中止,因此我只想發出通知。

也許有一種方法可以禁用Symfonys捕獲某些異常或某些控制器?

+0

我想你可以通過覆蓋Twig異常處理程序來完成它。但我不是100%確定的。請參閱下面的答案。 – codecowboy 2012-08-16 17:03:46

回答

3

當你這樣做$this->container->get("mailer")->send($email);如果你打開了假脫機處理,那麼電子郵件不會被髮送。請參閱http://symfony.com/doc/current/cookbook/email/spool.html

如果您的默認設置爲spool: { type: memory },則在控制器退出後,將在內核終止階段拋出\Swift_TransportException。 解決此問題的一個方法是關閉後臺處理(但用戶可能必須等待郵件發送時),或者您可以讓自己的eventlistener處理異常。 http://symfony.com/doc/current/cookbook/service_container/event_listener.html

0

你可以嘗試覆蓋樹枝異常處理程序在config.yml:

twig: 
    debug:   %kernel.debug% 
    strict_variables: %kernel.debug% 
    exception_controller: MyBundleName:Exception:show 

然後創建延伸的Exception類:

的Symfony \包\ TwigBundle \控制器\ ExceptionController

讀取該文件的源代碼,然後覆蓋方法以在異常類型爲Swift_TransportException時切換顯示哪個模板

可以做到這一點通過設置的showAction()的一類可變並將它傳遞給findTemplate()

的showAction:

$這 - > exceptionClassName = $ exception->的getClass();

findTemplate:

if (!$debug && $this->exceptionClassName == 'MyBundle\Exception\GenericNotFoundException') { 

      return 'BundleName:Exception:generic404.html.twig'; 
     } 

欲瞭解更多信息,我建議KNPUniversity Symfony的截屏。