From 4e296722545779411cff27a08d07eccdfd465462 Mon Sep 17 00:00:00 2001 From: Giorgio Premi Date: Wed, 29 Dec 2021 12:22:26 +0100 Subject: [PATCH] MailerInterface: failed exception contract when enabling messenger The interface for MailerInterface::send states that exception for transport failures are sent as TransportExceptionInterface, which make perfectly sense and allows to create solid UI. If at later stage the Messenger component is enabled, the mail will be rewired into a dispatched message, which by default is synchronous. This cause all exception to be wrapped into HandlerFailedException which doesn't the interface contract. In the end the UI is broken, and the exception HandlerFailedException, even if caught, is totally unrelated to the usage context as it is only related to configuration details. This patch will unwrap the underlying MailTransportInterface exception if available for the handler exception. --- src/Symfony/Component/Mailer/Mailer.php | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/Symfony/Component/Mailer/Mailer.php b/src/Symfony/Component/Mailer/Mailer.php index 260989e72166a..2458544141cd3 100644 --- a/src/Symfony/Component/Mailer/Mailer.php +++ b/src/Symfony/Component/Mailer/Mailer.php @@ -13,8 +13,10 @@ use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy; use Symfony\Component\Mailer\Event\MessageEvent; +use Symfony\Component\Mailer\Exception\TransportExceptionInterface; use Symfony\Component\Mailer\Messenger\SendEmailMessage; use Symfony\Component\Mailer\Transport\TransportInterface; +use Symfony\Component\Messenger\Exception\HandlerFailedException; use Symfony\Component\Messenger\MessageBusInterface; use Symfony\Component\Mime\RawMessage; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; @@ -50,6 +52,15 @@ public function send(RawMessage $message, Envelope $envelope = null): void $this->dispatcher->dispatch($event); } - $this->bus->dispatch(new SendEmailMessage($message, $envelope)); + try { + $this->bus->dispatch(new SendEmailMessage($message, $envelope)); + } catch (HandlerFailedException $e) { + foreach ($e->getNestedExceptions() as $nested) { + if ($nested instanceof TransportExceptionInterface) { + throw $nested; + } + } + throw $e; + } } }