问题
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