【问题标题】:Catch Exception in Cakephp 3 : not working在 Cakephp 3 中捕获异常:不工作
【发布时间】:2015-12-10 17:29:32
【问题描述】:

我尝试在 Cakephp v3.0 中捕获异常,但它似乎不起作用:

    try{
    $email = new Email('default');
    $email->from([Configure::read('email') => Configure::read('emailName')])
        ->to(Configure::read('email'))
        ->bcc($to)
        ->subject(__('XXXX') . ' : ' . __('XXXX'))
        ->template('fail', 'default')
        ->emailFormat('html')
        ->send();
} catch (Exception $ex) {
}

它没有捕捉到异常:

Could not send email: mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() Cake\Network\Exception\SocketException

很烦人,我用它来捕捉本地服务器上发送失败的电子邮件。

非常感谢。

【问题讨论】:

  • 您指向一个导入的类,或者指向与当前类在同一命名空间中的一个类,因此请检查您的代码中的 Exception 实际指的是什么 - 如果我猜的话,我会说它可能不是全局命名空间中的本机 \Exception 类。 ps,请务必在发布错误时包含堆栈跟踪和上下文信息!
  • 使用 RuntimeException 而不是 Exception,成功了。谢谢!
  • @Gael.D 我一直在为这个问题而苦恼。使用您的解决方案。没有任何输出。

标签: php cakephp exception cakephp-3.0


【解决方案1】:

在此处添加答案,只是为了降低未回答问题的统计数据:

您需要使用\Exception 或更具体的、命名空间的异常名称

try {
    // code
} catch (\Exception $e) {
    // error
}

【讨论】:

  • 100 年后我都不会想到这一点。
  • @JoeC JoseLorenzo 是 cakephp 的创始人/所有者
  • 这个答案没有 CakePHP 魔法,它是基本的 PHP 命名空间。
【解决方案2】:

当我试图捕捉 MissingConnectionException 时,我遇到了类似的问题。

就我而言,以下几行解决了我的问题。

use Cake\Core\Exception\Exception;
...
try {
    // Your test code here
} catch (Exception $e) {
    ...
}

希望对你有所帮助。

【讨论】:

    【解决方案3】:

    您可以尝试使用try - catch

    try {
       $email = new Email('default');
       $email->from([Configure::read('email') => Configure::read('emailName')])
        ->to(Configure::read('email'))
        ->bcc($to)
        ->subject(__('XXXX') . ' : ' . __('XXXX'))
        ->template('fail', 'default')
        ->emailFormat('html')
        ->send();
    } catch (\PDOException $e) {
        $error = $e->getMessage();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 2022-12-02
      相关资源
      最近更新 更多