Laravel尝试捕获不起作用,无法捕获包中的异常

时间:2018-08-03 08:40:35

标签: php laravel laravel-5 laravel-exceptions

我正在使用软件包https://github.com/barbushin/php-imap从邮件服务器读取电子邮件,我有以下代码

$folder = Storage::disk('local')->getAdapter()->getPathPrefix();
try {
    $mailbox = new \PhpImap\Mailbox('{imap.gmail.com:993/imap/ssl}INBOX', 'xxxxx@gmail.com', 'xxxxxxxxxx', $folder);    
}
catch(\Exception $e) {
    return 'rroor';
}

但没有捕获错误,如果登录失败,我想记录该错误。

以下代码引发异常

if(!$result) {
    $errors = imap_errors();
    if($errors) {
        if($throwExceptionClass) {
            throw new $throwExceptionClass("IMAP method imap_$methodShortName() failed with error: " . implode('. ', $errors));
        }
        else {
            return false;
        }
    }
}

如何在我的控制器方法上捕获此异常?

查看错误页面

enter image description here

3 个答案:

答案 0 :(得分:2)

您只能在try ... catch中使用类构造函数。我看着仓库,似乎没有从构造函数中抛出该异常。 https://github.com/barbushin/php-imap/blob/master/src/PhpImap/Mailbox.php#L33

您的代码中还有更多内容可以调用代码https://github.com/barbushin/php-imap/blob/master/src/PhpImap/Mailbox.php#L148的这一部分吗?

我认为您需要将更多代码包装到示例中缺少的try ... catch中。

答案 1 :(得分:0)

尝试一下:

use PhpImap\ConnectionException;

//....

$folder = Storage::disk('local')->getAdapter()->getPathPrefix();
try {
    $mailbox = new \PhpImap\Mailbox('{imap.gmail.com:993/imap/ssl}INBOX', 'xxxxx@gmail.com', 'xxxxxxxxxx', $folder);    
}
catch(ConnectionException $e) {
    return 'rroor';
}

或编辑您的App \ Exceptions \ Handler;

public function render($request, Exception $exception)
{
    if ($exception instanceof \PhpImap\ConnectionException\ConnectionException) {
       //add log
       return 'error';
    }
    return parent::render($request, $exception);
}

答案 2 :(得分:0)

try {
    $folder = Storage::disk('local')->getAdapter()->getPathPrefix();
    $mailbox = new \PhpImap\Mailbox('{imap.gmail.com:993/imap/ssl}INBOX', 
   'xxxxx@gmail.com', 'xxxxxxxxxx', $folder);    
}
catch(\Throwable $e) {
   return 'error';
}
相关问题