【发布时间】:2016-01-01 19:44:11
【问题描述】:
PHP 只记录未捕获的异常。我还想记录我所有的捕获异常。
示例 1
try {
$book->getBook();
} catch( Exception $e ) {
error_log( $e );
$error = 'A problem occurred getting your book'
}
这很好用,但我不想到处写error_log。
因此,我像这样扩展了 Exception 类:
示例 2
class ExceptionLog extends Exception {
public function __construct( $message, $code = 0, Exception $previous = null ) {
error_log( $this );
parent::__construct($message, $code, $previous);
}
}
我可以这样做:
try {
$book->getBook();
} catch( ExceptionLog $e ) {
$error = 'A problem occurred getting your book'
}
这里的一个问题是记录的消息略有不同。在第一个示例中,日志条目是:
[01-Jan-2016 19:24:51 Europe/London] PHP Fatal error: Uncaught exception 'Exception' with message 'Could not get book' in book.php:39
在第二个例子中,消息被省略:
[01-Jan-2016 19:24:51 Europe/London] exception 'ExceptionLog' in book.php:39
是访问父类Exception 的属性并手动构建错误日志字符串的唯一方法吗?
【问题讨论】:
标签: php exception error-handling exception-handling