Cakephp 3中捕获异常:不工作
我试图在Cakephp v3.0中捕获异常,但它似乎不起作用:Cakephp 3中捕获异常:不工作,php,cakephp,exception,cakephp-3.0,Php,Cakephp,Exception,Cakephp 3.0,我试图在Cakephp v3.0中捕获异常,但它似乎不起作用: try{ $email = new Email('default'); $email->from([Configure::read('email') => Configure::read('emailName')]) ->to(Configure::read('email')) ->bcc($to) ->subject(__('XX
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
或更具体的、命名空间的异常名称
try {
// code
} catch (\Exception $e) {
// error
}
当我试图捕获
丢失的ConnectionException
时,我遇到了类似的问题
在我的例子中,以下几行解决了我的问题
use Cake\Core\Exception\Exception;
...
try {
// Your test code here
} catch (Exception $e) {
...
}
希望对您有所帮助。您可以尝试使用
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();
}
您正在指向导入的类,或者指向与当前类位于同一命名空间中的类,因此请检查代码中的
Exception
实际上指的是什么-如果我猜的话,我会说它可能不是全局命名空间中的本机\Exception
类。ps,在发布错误时,请始终包含堆栈跟踪和上下文信息!使用RuntimeException而不是Exception,成功了。谢谢@盖尔:我一直在忍受这个问题。使用你的解决方案。没有任何输出。100年来我都不会想到这一点。@JoeC JoseLorenzo是CakePHP的创始人/所有者。这个答案没有CakePHP的魔力,它是基本的PHP名称空间。