如何在yii2中使用try catch异常发送参数?

时间:2017-03-23 07:30:22

标签: yii2

我在发送电子邮件时遇到问题,看起来我们的服务器连接到邮件服务器是不稳定的,有时它成功发送,但有时它不是,它说ssl超时。

所以我的想法是捕获超时异常并插入数据库然后我可以稍后发送。

但我需要发送一些带有catch异常的参数,这样我才能正确插入数据库。

到目前为止我想要的是这样的

try{
  $message = Yii::$app->mail->compose();
  if (Yii::$app->user->isGuest) {
    $message->setFrom('from@domain.com');
  } else {
    $message->setFrom(Yii::$app->user->identity->email);
  }
  $message->setTo(Yii::$app->params['adminEmail'])
  ->setFrom(Yii::$app->params['adminEmail'])
  ->setTo("mymail@gmail.com")
  ->setSubject('Title 1')
  ->setHtmlBody("Hi, this is my content to check if registration email successfully sent")
  ->send();
  $mail_from = "no-reply@myweb.com";
  $mail_to = "customer@someweb.com";
  $content = "here is content of email"
  $other = "this other variable";
  return 1;

}catch(\Swift_TransportException $e, $mail_from, $mail_to, $content, $other){

  //if connection time out or something
  $queue = new Queue;
  $queue->mail_from = $mail_from;
  $queue->mail_to = $mail_to;
  $queue->content = $content;
  $queue->other = $other;
  $queue->fail_reason = $e->getMessage();
  $queue->save()
}

但它给了我undefined variable $mail_from, $mail_to, and etc

我如何解决问题?

提前致谢。

1 个答案:

答案 0 :(得分:0)

要解决undefined variable $mail_from, $mail_to, and etc错误,最好在try块之外声明变量。因为您在try的末尾声明了变量,所以在这些变量初始化之前它就会失败。

$mail_from = "no-reply@myweb.com";
$mail_to   = "customer@someweb.com";
$content   = "here is content of email"
$other     = "this other variable";

try {
    $message = Yii::$app->mail->compose();

    if (Yii::$app->user->isGuest) {
        $message->setFrom('from@domain.com');
    } else {
        $message->setFrom(Yii::$app->user->identity->email);
    }
    $message->setTo(Yii::$app->params['adminEmail'])
        ->setFrom(Yii::$app->params['adminEmail'])
        ->setTo("mymail@gmail.com")
        ->setSubject('Title 1')
        ->setHtmlBody("Hi, this is my content to check if registration email successfully sent")
        ->send();

    return 1;
} catch(\Swift_TransportException $e) {
    //if connection time out or something
    $queue = new Queue;
    $queue->mail_from = $mail_from;
        $queue->mail_to = $mail_to;
    $queue->content = $content;
    $queue->other = $other;
    $queue->fail_reason = $e->getMessage();
    $queue->save()
}

但此代码存在更多问题。您多次设置fromto部分。在if/else您正在调用setFrom,然后再过几行。 setTo也是如此。对函数的最后一次调用将否决先前的设定值。因此,请确保只调用一次这些函数。

相关问题