Catch swiftmailer exception in Symfony2 dev env controller
Asked Answered
T

2

10

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?

Toots answered 15/7, 2012 at 21:36 Comment(1)
I think you might be able to do it by overriding the Twig Exception handler. I am not 100% sure though. See my answer below.Antimagnetic
C
3

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

Collie answered 11/10, 2014 at 22:1 Comment(0)
A
0

You can try overriding the Twig Exception Handler in config.yml:

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

You then create an Exception class which extends:

Symfony\Bundle\TwigBundle\Controller\ExceptionController

Read the source code of that file and then override the methods to switch which template is rendered when the Exception type is Swift_TransportException

You can do that by setting a class variable in showAction() and passing it to findTemplate()

showAction:

$this->exceptionClassName = $exception->getClass();

findTemplate:

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

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

For more information, I recommend the KNPUniversity Symfony Screencasts.

Antimagnetic answered 16/8, 2012 at 16:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.