2014-09-22 51 views
2

如何在symfony控制器/ swift消息中抑制错误消息,例如如果用户不存在的邮件,什么是错与SMPT服务器或电子邮件地址根本不符合RFC 2822Symfony/Twig中的Supress错误消息?

例如,我们得到了以下关键错误...

request.CRITICAL:Swift_RfcComplianceException:给定邮箱中的地址[[email protected]]不符合RFC 2822,3.6.2。 (未捕获的异常)在$

...用户然后得到一个symfony错误页面“An Error occured”,我需要在任何情况下禁止。

一个简单的@ $ this-> get('mailer') - > send($ message);没有在这里不幸的是工作...

protected function generateEmail($name) 
{ 
     $user = $this->getDoctrine() 
      ->getRepository('XXX') 
      ->findOneBy(array('name' => $name)); 

     if (!$user) { 
      exit(); 
     } 
     else { 
      $message = \Swift_Message::newInstance() 
      ->setSubject('xxx') 
      ->setFrom(array('[email protected]' => 'xxx')) 
      ->setTo($user->getEmail()) 
      ->setContentType('text/html') 
      ->setBody(
       $this->renderView(
        'AcmeBundle:Template:mail/confirmed.html.twig' 
       ) 
      ) 
      ; 
      $this->get('mailer')->send($message); 
      // a simple @$this->get('mailer')->send($message); doesn't work here 
     } 

    return true; 
} 

回答

1

我不知道,一个try catch块将工作,因为邮件可以稍后在请求过程中发送:如果您使用的框架完整的堆栈版本http://symfony.com/fr/doc/current/components/http_kernel/introduction.html#l-evenement-kernel-terminate

,这是默认的行为。

我也发现了一些裁判在这里:Unable to send e-mail from within custom Symfony2 command but can from elsewhere in app

你可以改变你的配置的Swiftmailer阀芯策略发送直邮...

+0

嗨Yann,这很有趣,我将不得不尝试一下! – Mike 2014-10-03 10:55:18

4

要简单地取消错误,在块包发送方法。明智地选择例外类型。以下示例仅捕获Swift_RfcComplicanceExceptions

try { 
    $this->get('mailer')->send($message); 
} catch (\Swift_RfcComplianceException $exception) { 
    // do something like proper error handling or log this error somewhere 
} 

我认为最好事先应用一些验证,以便您可以向用户显示一个很好的错误。

+0

嘿devsheeep,谢谢,关于向Yanns评论下面,我如果作品会尝试。但你的回答对我来说似乎很好! – Mike 2014-10-03 10:55:53