caseycs/php-error-handler

通用错误、异常和可缓存的致命错误处理器

dev-master 2015-03-06 20:46 UTC

This package is not auto-updated.

Last update: 2024-09-23 15:56:20 UTC


README

使用回调进行常见错误处理。为每个错误提供包含请求URL、引用者、会话和其他环境信息的自定义错误消息。

示例

SHUTDOWN Call to undefined function unexisted_function() in /Users/ikondrashov/github/php-error-handler/test/uncatchable.php:6
URL: localhost:3000/uncatchable.php
HTTP_REFERER: https://:3000/uncatchable.php
SESSION: Array
(
    [a] => 5
)
POST: Array
(
    [b] => 10
)
COOKIES: Array
(
    [c] => 15
)
uniqid: 52496cfee1616

通过Composer安装

{
    "require": {
        "caseycs/php-error-handler": "dev-master"
    },
}

使用方法

基本使用

$ErrorHandler = new ErrorHandler\ErrorHandler;
$ErrorHandler->register();

高级使用

if ($_SERVER['APPLICATION_ENV'] !== 'development') {
    $ErrorHandler = new ErrorHandler\ErrorHandler;
    $ErrorHandler->register();
    $ErrorHandler->addExceptionCallback(function () {header ('HTTP/1.0 500 Internal Server Error', true, 500);});
}

深入了解

首先 - 确保你已经定义了error_log值 - 对于cli和fpm(或apache)环境。对于Web使用phpinfo(),对于CLI使用php -i | grep error_log。确保指定的文件可以被执行CLI脚本的用户(例如使用crontab)和apache/fpm写入。

这非常重要!

同时,确保display_errors等于false - 此包仅用于生产使用。

我们的目标是什么?

对于CLI,我们将所有错误写入常见的CLI错误日志/var/log/php-errors-cli.php,并将其写入正在运行的脚本的stderr - 例如来自crontab的* * * * * php script.php >>> script.log 2>&1

对于Web,我们将所有错误写入常见的Web错误日志/var/log/php-errors-fpm.php,包括环境 - URL、引用者、GET、POST、cookies、会话等。我们还希望将环境写入不可捕获的错误 - 这些错误由register_shutdown_function处理。

缺点

未被set_error_handler处理的致命错误,仅由register_shutdown_function捕获,在错误日志中会显示两次 - 第一次是原生的PHP错误,第二次是我们的带有环境信息的自定义消息。有人知道如何解决这个问题吗?