Catch swiftmailer exception in Symfony2 dev env controller

扶醉桌前 提交于 2019-12-12 07:48:53

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/11495804/catch-swiftmailer-exception-in-symfony2-dev-env-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!