Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch swiftmailer exception in Symfony2 dev env controller

Im not sure why Im not catching exceptions from Swiftmailer in my controller. What am I doing wrong, or missing?

In a controller I have:

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

It seems to get caught by Symfony before it gets to my code, so instead of being able to handle the error myself I get the standard 500 page with Swift_TransportException: Connection could not be established

If the email can't be sent there is no need for the application to halt as the email isn't critical - I just want to issue a notice.

Maybe there's a way to disable Symfonys catching of certain exceptions or for certain Controllers?

like image 458
petesiss Avatar asked Jul 15 '12 21:07

petesiss


1 Answers

When you do $this->container->get("mailer")->send($email); the email message is not being sent at that point if you have spooling turned on. See http://symfony.com/doc/current/cookbook/email/spool.html

If you have the default setting of spool: { type: memory }, the \Swift_TransportException will be thrown during the kernel termination phase, after your controller has exited. One way around this is to turn off the spooling (but then your users might have to wait while the email is sent), or you can make your own eventlistener to handle the exception. http://symfony.com/doc/current/cookbook/service_container/event_listener.html

like image 192
Terje Bråten Avatar answered Oct 21 '22 14:10

Terje Bråten