我有一些错误处理代码,试图确保在一定水平上捕获并处理任何问题,因此我使用了set_error_handler
将可恢复的错误转换为异常,然后捕获所有异常。想法是代码是遇到一些可恢复的错误,还是引发异常,这应该捕获所有错误。但是,我看到的是正在发生可重试的错误,该错误被转换为异常,然后没有被我的捕获捕获。不明白为什么。
public function catchableFatalErrorCatcher($errno, $errstr) : bool
{
if (error_reporting() !== 0 && $errno === E_RECOVERABLE_ERROR)
{
throw new ParseException($errstr, $errno); //extends \Exception
}
return false;
}
public function evaluate($cmd)
{
$prevErrorHandler = set_error_handler([$this, 'catchableFatalErrorCatcher']);
try
{
$tokens = $this->tokenize($cmd);
$value = $this->parse($tokens, $this->model);
if (is_array($value))
{
// IN THE FAILURE CASE, $value IS AN ARRAY OF OBJECTS AND THIS
// CAUSES AN ERROR BECAUSE THE ELEMENTS CAN'T BE TURNED INTO STRINGS.
$value = implode(', ', $value);
}
return strval($value);
}
catch (ParseException $e)
{
if ($this->trace !== null)
{
$this->trace .= $e->getMessage() . "\n";
}
return '';
}
finally
{
set_error_handler($prevErrorHandler);
}
}
我最终在我的网站上遇到HTTP错误500,并在我的php错误中记录了消息:PHP Warning: Uncaught <<redacted>>\ParseException: Object of class <<redacted>> could not be converted to string
。堆栈跟踪清楚地表明,由于上面提到的内爆调用,正在调用错误处理程序。怎么不被抓住!?
答案 0 :(得分:-2)
## Please Use Below code
public function catchableFatalErrorCatcher($errno, $errstr) : bool
{
if (error_reporting() !== 0 && $errno === E_RECOVERABLE_ERROR)
{
throw new Exception($errstr, $errno);
}
return false;
}
public function evaluate($cmd)
{
$prevErrorHandler = set_error_handler([$this, 'catchableFatalErrorCatcher']);
try
{
$tokens = $this->tokenize($cmd);
$value = $this->parse($tokens, $this->model);
if (is_array($value))
{
// IN THE FAILURE CASE, $value IS AN ARRAY OF OBJECTS AND THIS
// CAUSES AN ERROR BECAUSE THE ELEMENTS CAN'T BE TURNED INTO STRINGS.
$value = implode(', ', $value);
}
return strval($value);
}
catch (Exception $e)
{
if ($this->trace !== null)
{
$this->trace .= $e->getMessage() . "\n";
}
return '';
}
finally
{
set_error_handler($prevErrorHandler);
}
}