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类的属性并手动构建错误日志字符串的唯一方法吗?

最佳答案

您是否注意到从未使用过您的自定义错误消息?

造成这种情况的原因有两个:在“ExceptionLog”类构造函数中,您在调用父“Exception”类构造函数之前记录了错误,并且从未向“ExceptionLog”类构造函数提供自定义错误消息。

您的ExceptionLog类应如下所示:

class ExceptionLog extends Exception {
  public function __construct($message, $code = 0, Exception $previous = null) {
    parent::__construct($message, $code, $previous);
    error_log($this);
  }
}

然后,在“Book”类中,具有方法“getBook()”,该方法将引发您的自定义错误(请注意,我出于演示目的明确地抛出了该错误):
class Book {
  public function getBook() {
    throw new ExceptionLog('A problem occurred getting your book');
  }
}

看看如何将自定义错误消息传递给“ExceptionLog”类构造函数?然后,您可以创建“Book”类的实例:
$book = new Book();

并将try/catch更改为以下内容:
try {
  $book->getBook();
} catch (ExceptionLog $e) {
  //Custom error message is already defined
  //but you can still take other actions here
}

哪个应该产生类似于我在“php_error.log”文件中看到的错误:
[01-Jan-2016 21:45:28 Europe/Berlin] exception 'ExceptionLog' with message 'A problem occurred getting your book' in /Applications/MAMP/htdocs/php_exception_test/index.php:13

08-26 02:36