codeDragon codeDragon - 1 year ago 152
PHP Question

Silex Swiftmailer Swift_TransportException uncatchable

I am developing a web applicationen on base of the silex framework with decent Mail functionality. Sending mails works fine with the basic configuration and established connection to the mail server. In the case of errors e.g. due to connection loss, i want to log the causes and prevent them to be sent to the client. But iam unable to catch the mailer errors, especially the Swift_TransportException. I encapsulated the call of the 'send' function and also added an Error handler, both without success. Is this a bug, or am i missing something?

The error handler:

$app->error(function (\Swift_TransportException $e, Request $request, $code) {
//TODO log

The usage of the send function:

$message = \Swift_Message::newInstance()

catch(\Swift_TransportException $exception)
//TODO log

Answer Source

I found a solution to my problem in this post:


To sum it up, the problem was caused by the default behaviour of the swiftmailer in silex. By default the mails aren't send directly at code execution time, but buffered and send after the request result is returned to the client. Therefore errors aren't caught in the try block. To change this behavior i added slightly modified code from the referenced post to my mailer registration.

$app->register(new Silex\Provider\SwiftmailerServiceProvider());
$app['mailer'] = new \Swift_Mailer($app['swiftmailer.transport']);

thanks to igor for the good explanation.