3

How can I suppress error messages in a symfony controller / swift message, e.g. if the email of the user doesn't exist, something is wrong with the smpt server or the email address simply doesn't comply with RFC 2822.

For example, we got following CRITICAL error...

request.CRITICAL: Swift_RfcComplianceException: Address in mailbox given [ xxx@xxx.com ] does not comply with RFC 2822, 3.6.2. (uncaught exception) at $

... the user then get's a symfony error page "An Error occured" which I need to suppress in any case.

A simple @$this->get('mailer')->send($message); doesn't work here unfortunately ...

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('xxx@xxx.com' => '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;
}
Mike
  • 2,686
  • 7
  • 44
  • 61

2 Answers2

4

To simply suppress the error, wrap the send method in a try-catch block. Choose the exception type wisely. The following example just catches Swift_RfcComplicanceExceptions.

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

I'd consider it advisably to apply some validation beforehand, so you can display a nice error to your user.

devsheeep
  • 2,076
  • 1
  • 22
  • 31
  • Hey devsheeep, thanks, regarding to Yanns comment below, I'll try it if works. But your answer seems good to me! – Mike Oct 03 '14 at 10:55
1

I'm not sure that a try catch block will work, because mails may be sent later in the request process : http://symfony.com/fr/doc/current/components/http_kernel/introduction.html#l-evenement-kernel-terminate

If you use the framework Full Stack edition, this is the default behavior.

I've also found some refs here : Unable to send e-mail from within custom Symfony2 command but can from elsewhere in app

You can change the Swiftmailer spool strategy in your config to send direct mails...

Community
  • 1
  • 1
Yann Eugoné
  • 1,311
  • 1
  • 8
  • 17