Catch Exception in Cakephp 3 : not working

隐身守侯 提交于 2019-12-04 18:19:56

问题


I try to catch exceptions in Cakephp v3.0, but it doesn't seems to work :

    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) {
}

It doesn't catch the exception :

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

Pretty annoying, I'm using it to catch fail email send on a local server.

Thanks a lot.


回答1:


Adding the answer here, just to bring dow the unanswered questions stats down:

You need to use \Exception or a more specific, namespaced, exception name

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



回答2:


I had a similar issue when I tried to catch MissingConnectionException.

In my case, following lines solved my problem.

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

Hope it would be help for you.




回答3:


You could try using 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();
}


来源:https://stackoverflow.com/questions/32569444/catch-exception-in-cakephp-3-not-working

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