【发布时间】:2011-05-12 15:08:24
【问题描述】:
请考虑以下代码:
<?php
class MyException extends Exception {}
function global_exception_handler($exception)
{
switch (get_class($exception)) {
case 'MyException':
print "I am being handled in a unified way.\n";
break;
default:
$backtrace = debug_backtrace();
$exception_trace_object = $backtrace[0]['args'][0];
var_dump($exception_trace_object);
print "----\n";
$reflected_exception_trace_object = new ReflectionObject($exception_trace_object);
$reflected_trace_property = $reflected_exception_trace_object->getProperty('trace');
$reflected_trace_property->setAccessible(true);
var_dump($reflected_trace_property);
print "----\n";
// NOT WORKING, I STUCK HERE.
var_dump($reflected_trace_property->getValue($reflected_trace_property));
throw $exception;
}
}
set_exception_handler('global_exception_handler');
function function1()
{
function2();
}
function function2()
{
function3();
}
function function3()
{
throw new Exception();
}
function1();
?>
我想要做的是通过简单地设置一个全局异常处理程序以统一的方式跨各种文件处理各种类型的异常,而无需编写任何样板代码(除了页眉和页脚包含在每个文件中文件)。
问题是当抛出的异常类型没有被全局异常处理程序处理并且我想重新抛出异常时,堆栈跟踪会丢失,这是使用 set_exception_handler() 的限制。
我可以使用 debug_backtrace() 检索堆栈跟踪,但我无法访问其相关的私有成员以便能够正确打印它。
这是上面脚本产生的结果:
object(Exception)#1 (7) {
["message":protected]=>
string(0) ""
["string":"Exception":private]=>
string(0) ""
["code":protected]=>
int(0)
["file":protected]=>
string(28) "/home/laci/download/test.php"
["line":protected]=>
int(42)
["trace":"Exception":private]=>
array(3) {
[0]=>
array(4) {
["file"]=>
string(28) "/home/laci/download/test.php"
["line"]=>
int(37)
["function"]=>
string(9) "function3"
["args"]=>
array(0) {
}
}
[1]=>
array(4) {
["file"]=>
string(28) "/home/laci/download/test.php"
["line"]=>
int(32)
["function"]=>
string(9) "function2"
["args"]=>
array(0) {
}
}
[2]=>
array(4) {
["file"]=>
string(28) "/home/laci/download/test.php"
["line"]=>
int(45)
["function"]=>
string(9) "function1"
["args"]=>
array(0) {
}
}
}
["previous":"Exception":private]=>
NULL
}
----
object(ReflectionProperty)#3 (2) {
["name"]=>
string(5) "trace"
["class"]=>
string(9) "Exception"
}
----
NULL
Fatal error: Exception thrown without a stack frame in Unknown on line 0
提前致谢!
【问题讨论】:
标签: php exception global handler