php – ErrorException返回错误的文件和行
发布时间:2020-12-13 16:46:18 所属栏目:PHP教程 来源:网络整理
导读:在file1.php中: set_error_handler('my_error_handler');set_exception_handler('my_exception_handler');function my_error_handler($errNo,$errStr,$errFile,$errLine,$whatever = null){ // here ErrFile and $errLine are correct only for native func
在file1.php中:
set_error_handler('my_error_handler'); set_exception_handler('my_exception_handler'); function my_error_handler($errNo,$errStr,$errFile,$errLine,$whatever = null){ // here ErrFile and $errLine are correct only for native funcs... throw New ErrorException($errStr,$errNo,$errLine); } function my_exception_handler($exception){ print $exception->getLine(); // correct only for native functions print $exception->getFile(); // correct only for native functions } 在file2.php中,一个示例函数定义: function foo($requiredArg){ } 在file3.php中,调用foo: foo(); 生产:
这个消息是正确的,但是当我尝试使用$exception-> getFile()和$exception-> getLine()(在我的异常处理程序中)获取文件和行时,我得到文件和行foo()被定义,而不是被称为…… 但是使用本机PHP函数,我得到调用函数的文件和行(这就是我想要的). 解决方法
好问题!
对于本机和用户定义的函数,事情似乎表现得不同.但是,一个显而易见的事情是,无法真正告诉你函数的定义在哪里,如果它是原生的,因为它是用C语言编写的,而不是PHP.在用户空间代码的情况下,很高兴找到它被调用的位置.一种方法是从捕获的异常中解析该错误消息,您可以获取创建它的文件和行. function my_exception_handler($exception) { $message = $exception->getMessage(); $file = $exception->getFile(); $line = $exception->getLine(); if(strpos($message,'called in') !== false) { preg_match('/called in .*php/',$message,$matches); $file = str_replace('called in ','',$matches[0]); preg_match('/on line d/',$matches); $line = str_replace('on line ',$matches[0]); } echo 'line: ' . $line . PHP_EOL; echo 'file: ' . $file . PHP_EOL; } 基于输出的描述来自问题,改变了my_exception_handler: line: 4 file: /tmp/file3.php (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |