swiftmailer Swift_TransportException gets uncaught by try-catch block

走远了吗. 提交于 2019-12-12 08:12:45

问题


For a project (which is about estate properties) i have included a contact form where a visitor can contact an estate broker if the visitor is interested to buy/hire an estate property.

I am using Symfony2 and its library. For the contact mail, i am using the Swiftmailer library. Well, i have the next code which handles the form submit. there, I create a mail object to be able to send mails. It works, but i want to provide a error resolving service if there are problems with the smtp host from sender/receiver.

Here is the code,

$data = $contactForm->getData();
try {
    // create body text
    $body = $app['twig']->render('mailTemplate.twig', array('data' => $data, 'immoid' => $immoID));
    // set mail
    $mail = \Swift_Message::newInstance()
        ->setSubject('Contact reaction on your immo offer.')
        ->setFrom($app['swiftconfig']['sender'])
        ->setTo($contactinfo['contactmail'])
        ->setBody($body, 'text/html');
    // send mail
    $app['mailer']->send($mail);
    // redirect if successfull
    $app->redirect($app['url_generator']->generate('immoDetail', array('immoID' => $immoID)));
}
catch (Swift_TransportException $STe) {
    // logging error
    $string = date("Y-m-d H:i:s")  . ' - ' . $STe->getMessage() . PHP_EOL;
    file_put_contents("errorlog.txt", $string, FILE_APPEND);
    // send error note to user
    $errorMsg = "the mail service has encountered a problem. Please retry later or contact the site admin.";
}
catch (Exception $e) {
    // logging error
    $string = date("Y-m-d H:i:s")  . ' - GENERAL ERROR - ' . $e->getMessage() . PHP_EOL;
    file_put_contents("errorlog.txt", $string, FILE_APPEND);
    // redirect to error page
    $app->abort(500, "Oops, something went seriously wrong. Please retry later !");
}

($app['swiftconfig']['sender'] = mailaddress from host / $contactinfo['contactmail'] = mailaddress from site visitor (submitted in contact form))

Now, when the smtp host doesn't work, Swiftmailer DOES send an exception, but the try-catch block ISN'T catching it. The function is just being continued. Even the root try-catch block (in app.php) isn't catching it too. As a result of this, you see a large PHP error on the webpage, which shouldn't happen. The message from it is described here below,

SCREAM: Error suppression ignored for
---
Fatal error: Uncaught exception 'Swift_TransportException' with message ' in C:\...\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\StreamBuffer.php on line 266
---
Swift_TransportException: Connection could not be established with host <output omitted>

Does anyone know why the try catch block isn't catching the custom exception ? I have investigated the class files and the progress, but i don't see any unusual activity.

I hope that someone can come with a solution to this because PHP errors shouldn't appear on site pages.


回答1:


remove from your config.yml spool: { type: memory }

Then you will be to add try catch like this

    try{
        $mailer = $this->getMailer();
        $response = $this->getMailer()->send($message);
    }catch(\Swift_TransportException $e){
        $response = $e->getMessage() ;
    }



回答2:


When you do $app['mailer']->send($mail); 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 you 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




回答3:


I ran into this problem in Laravel 4.2 when I added a SwiftMailerHandler to Monolog so it would email to me anything logged at a certain level or above. There was no way for me to catch the exception in the handler and it was thrown back to the browser. I solved it by subclassing SwiftMailerHandler:

<?php
/*******************************************************************************
* $Id: LogMailer.php 12152 2015-09-15 00:42:38Z sthames $ */
/**
* Subclass of Monolog SwiftMailerHandler that will catch exceptions SwiftMailer
* throws during the send. These exceptions are logged at the critical level.
* Without this, such exceptions are reported back to the browswer.
*******************************************************************************/
class LogMailer extends \Monolog\Handler\SwiftMailerHandler
  {
  /** Flag set when logging an exception during send. */
  protected $dont_mail = false;

  /** Overloads sender to catch and log errors during the send. */
  protected function send($content, array $records)
    {
    try
      {
      if (!$this->dont_mail)
        parent::send($content, $records);
      }
    catch(\Exception $e)
      {
      $this->dont_mail = true;
      Log::critical($e->getMessage());
      $this->dont_mail = false;
      }
    }
  }

This handler catches the SwiftMailer exception and logs it at the critical level so it's not lost. I don't get an email about it but at least it's in the log.

I was surprised to find SwiftMailerHandler offered no way to inject an exception handler into the send method but fortunately the code is written well enough to make this solution pretty simple.

Works great and has given me no trouble so far.




回答4:


Try to put a backslash infront of Exception.

catch(\Exception $e)

A \ (backslash) before the beginning of a class name represents the Global Namespace.

Using a backslash will ensure that the Exception is called within the global namespace.




回答5:


Sure you have the latest version of swiftmailer? Line 226 of StreamBuffer.php doesn't throw any exception. This version from 2 years ago does throw the exception on that specific line.

I'd try running the latest version before diving into the issue more deeply.




回答6:


SCREAM is a setting of XDebug that allows to see errors that are normally caught or suppressed. (Using @, for example.) Search for

xdebug.scream = 1

in your php.ini and set this to 0.




回答7:


you can try below code for custom error:

public function render($request, Exception $exception)
{
     if ($exception instanceof \Swift_TransportException) {
     return response()->view('errors.404');
}
     return parent::render($request, $exception);
}


来源:https://stackoverflow.com/questions/17695896/swiftmailer-swift-transportexception-gets-uncaught-by-try-catch-block

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