Search code examples
phplaravellaravel-5laravel-exceptions

Laravel try catch not working, cant catch exception from a package


I am using a package https://github.com/barbushin/php-imap to read email from mail server, I have the following code

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

but is not catching error, I want to log the error if login fails.

The following code is throwing the exception

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

How can I catch this exception on my controller method ?

see the error page

enter image description here


Solution

  • You only have the class constructor in the try...catch. I looked at the repo and it doesn't appear to throw that exception from the constructor. https://github.com/barbushin/php-imap/blob/master/src/PhpImap/Mailbox.php#L33

    Is there more to your code that may be calling this part of the code https://github.com/barbushin/php-imap/blob/master/src/PhpImap/Mailbox.php#L148?

    I think you need to wrap more of your code into the try...catch that's missing from your example.