如果我在PHP中没有捕获异常,我会在我的error.log
文件中得到一个带有堆栈跟踪的有用错误信息。例如,如果我运行:
<?php
function foo() {
throw new Exception('Oh no!');
}
foo();
?>
然后我会在日志中记录下以下内容:
[Wed Mar 06 10:35:32 2013] [error] [client 86.146.145.175] PHP致命错误: 在/var/www/test.php的第4行抛出了一个消息为"Oh no!"的异常\n堆栈跟踪:\n#0 /var/www/test.php(7): foo()\n#1 {main}\n
有时我想捕获异常,但仍要记录该详细信息。我的想法是像这样:
<?php
function foo() {
throw new Exception('Oh no!');
}
try {
foo();
} catch (Exception $e) {
log_exception($e);
}
?>
log_exception
函数会以与未捕获异常自动写入的基本相同格式写入错误日志,除了使用Caught exception
代替PHP Fatal error: Uncaught exception
之外,它们可能几乎完全相同。
是否有内置函数可以记录异常信息或将其捕获为字符串?我想象中的类似于Python中的traceback.format_exc()
的东西。
Exception
的toString
成员函数有什么“神奇”之处? - lmat - Reinstate Monica