【问题标题】:PHP log caught exceptionPHP日志捕获异常
【发布时间】: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


    【解决方案1】:

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

    这有两个原因:在您的“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
    

    【讨论】:

      猜你喜欢
      • 2012-01-06
      • 2014-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 1970-01-01
      • 2011-12-05
      • 1970-01-01
      相关资源
      最近更新 更多