0

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', 'xxxxx@gmail.com', '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

Joyal
  • 2,587
  • 3
  • 30
  • 45

3 Answers3

4

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.

Jason Grim
  • 413
  • 4
  • 7
2
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';
}
Arnab Rahman
  • 1,003
  • 1
  • 9
  • 15
1

Try this:

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';
}

Or edit your App\Exceptions\Handler;

public function render($request, Exception $exception)
{
    if ($exception instanceof \PhpImap\ConnectionException\ConnectionException) {
       //add log
       return 'error';
    }
    return parent::render($request, $exception);
}
J. Doe
  • 1,682
  • 11
  • 22