我正在 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] => ))我真的不在乎嘗試調用不存在的方法時是否發生錯誤或異常。我只是對為什么使用錯誤對象調用異常處理程序感到困惑。如果有人以前遇到過這個問題,希望能得到一些澄清。
1 回答

子衿沉夜
TA貢獻1828條經驗 獲得超3個贊
我發現有點令人困惑的是,它set_exception_handler不僅捕獲Exception對象Throwable,還Error捕獲對象(它們是Throwable對象,但不是Exception對象)。
我覺得這很令人困惑,因為set_error_handler其中有“錯誤”一詞,但它沒有捕獲這些對象類型。
因此,對于任何其他偶然發現這一點的人來說,在較新版本的 PHP 中,您不能期望Exception回調對象set_exception_handler。您需要期望 a 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。
希望這對其他人有幫助:)
- 1 回答
- 0 關注
- 126 瀏覽
添加回答
舉報
0/150
提交
取消