我正在使用PHP中的错误和异常句柄,并且在尝试调用不存在的方法时发现了一些意外行为。
这是PHP:
<?php
set_error_handler(function() {
echo 'error';
});
set_exception_handler(function() {
echo 'exception';
$args = func_get_args();
print_r($args);
});
$obj = new stdClass;
$obj->jdhgdfkjh();
exit(0);
这是输出:
exceptionArray
(
[0] => Error Object
(
[message:protected] => Call to undefined method stdClass::jdhgdfkjh()
[string:Error:private] =>
[code:protected] => 0
[file:protected] => /var/www/domain.com/index.php
[line:protected] => 11
[trace:Error:private] => Array
(
)
[previous:Error:private] =>
)
)
我真的不在乎是尝试调用不存在的方法时发生的错误还是异常。我只是对为什么使用错误对象调用异常处理程序感到困惑。如果有人之前遇到过这种情况,不妨澄清一下。
最佳答案
尽我所能回答我自己的问题。 @apokryfos是正确的:手册中对此有详细说明。我感到有点困惑,因为set_exception_handler
不仅捕获Exception
和Throwable
对象,而且捕获Error
对象(它们是Throwable
对象,但没有捕获Exception
对象)。
我觉得这很困惑,因为set_error_handler
中包含“错误”一词,但它并没有捕获这些对象类型。
因此,对于任何偶然发现此问题的人,在较新版本的PHP中,您不能期望Exception
回调具有set_exception_handler
对象。您需要期望Throwable
,并且非线性地,您还可能会得到Error
接收到的而不是的set_error_handler
对象。
为了在我自己的设置中处理此问题,我使用以下set_error_handler
使事情更简洁:
set_error_handler(function($errno, $errstr, $errfile, $errline, $errcontext) {
$args = array($errstr, $errno, E_ERROR, $errfile, $errline);
$errorException = new \ErrorException(... $args);
});
然后,您的set_exception_handler
回调将捕获该错误。希望这对其他人有帮助:)
关于php - 为什么PHP set_execption_handler捕获错误对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63293185/