try{...}catch 不会在 PHP/Symfony2/PHPImap 中抛出异常
try{...}catch does not throw exception in PHP/Symfony2/PHPImap
我正在使用 ImapMail 库并尝试启动一个新邮箱:
try{
$mailbox = new ImapMailbox($url, $username, $password);
}catch (\Exception $e){
return new Response("fail");
}
但是上面的 try/catch 不起作用,尽管 symfony 给了我这个:
Connection error: (is empty)
500 Internal Server Error - Exception
堆栈跟踪
in vendor/php-imap/php-imap/src/PhpImap/Mailbox.php at line 67:
protected function initImapStream() {
$imapStream = @imap_open($this->imapPath, $this->imapLogin, $this->imapPassword, $this->imapOptions, $this->imapRetriesNum, $this->imapParams);
if(!$imapStream) {
throw new Exception('Connection error: ' . imap_last_error());
}
return $imapStream;
}
(Direct link to function on github)
它确实抛出了一个新的异常,为什么我不能捕捉到它?
感谢任何提示!
原因很简单。您只在 try 块中调用 class 构造函数。如果您查看 class 源代码,您会发现构造函数没有调用任何内容。
https://github.com/barbushin/php-imap/blob/master/src/PhpImap/Mailbox.php#L20-L31
这意味着代码抛出异常必须在你下面try/catch。如果你想捕获异常,你必须将它移到 try 块中。我说的是 $mailbox->checkMailbox()
。此命令抛出异常。
我正在使用 ImapMail 库并尝试启动一个新邮箱:
try{
$mailbox = new ImapMailbox($url, $username, $password);
}catch (\Exception $e){
return new Response("fail");
}
但是上面的 try/catch 不起作用,尽管 symfony 给了我这个:
Connection error: (is empty)
500 Internal Server Error - Exception
堆栈跟踪
in vendor/php-imap/php-imap/src/PhpImap/Mailbox.php at line 67:
protected function initImapStream() {
$imapStream = @imap_open($this->imapPath, $this->imapLogin, $this->imapPassword, $this->imapOptions, $this->imapRetriesNum, $this->imapParams);
if(!$imapStream) {
throw new Exception('Connection error: ' . imap_last_error());
}
return $imapStream;
}
(Direct link to function on github)
它确实抛出了一个新的异常,为什么我不能捕捉到它?
感谢任何提示!
原因很简单。您只在 try 块中调用 class 构造函数。如果您查看 class 源代码,您会发现构造函数没有调用任何内容。
https://github.com/barbushin/php-imap/blob/master/src/PhpImap/Mailbox.php#L20-L31
这意味着代码抛出异常必须在你下面try/catch。如果你想捕获异常,你必须将它移到 try 块中。我说的是 $mailbox->checkMailbox()
。此命令抛出异常。