如何重新定义Slim v3的错误处理程序?

时间:2016-03-31 19:31:36

标签: php rest error-handling slim

我遵循了Slim v3文档,介绍了如何重新定义框架的内置错误处理程序,以防止错误输出到响应中,并使用以下代码:

$settings = require __DIR__ . '/../src/settings.php';
$app = new \Slim\App($settings);

// Errors to log rather than to end user
$c = $app->getContainer();

$c['errorHandler'] = function ($c) {
    return function ($request, $response, $exception) use ($c) {
        $c['logger']->error("Error 500 diverted: ".$exception->getMessage());
        return $c['response']->withStatus(500)
                             ->withHeader('Content-Type', 'text/html')
                             ->write('Something went wrong on our side!');
    };
};

然而我的API仍在吐出Slim的默认处理程序,其中包含完整的堆栈跟踪和告警Slim Application Error字符串...虽然有用,但我更倾向于将此信息发送到Slim的日志(monolog)和某些东西面对客户的不那么透露。有没有理由重新定义此服务重新定义?

1 个答案:

答案 0 :(得分:4)

此代码有效:

<?php
$app = new \Slim\App();
$container = $app->getContainer();

$container['errorHandler'] = function ($c) {
    return function ($request, $response, $exception) use ($c) {
        // log error here
        return $c['response']->withStatus(500)
                             ->withHeader('Content-Type', 'text/html')
                             ->write('Something went wrong on our side!');
    };
};
$container['phpErrorHandler'] = function ($c) {
    return function ($request, $response, $error) use ($c) {
        // log error here
        return $c['response']->withStatus(500)
                             ->withHeader('Content-Type', 'text/html')
                             ->write('Something went wrong on our side (again)!');
    };
};

$app->get('/exception', function ($req, $res, $args) {
    // errorHandler will trap this Exception
    throw new Exception("An error happened here");
});

$app->get('/php7', function ($req, $res, $args) {
    $x = function (int $x) {
        return $x;
    };

    // phpErrorHandler wil trap this Error
    $x('test');
});

$app->get('/warning', function ($req, $res, $args) {
    $x = UNDEFINED_CONSTANT;
});

$app->run();

如您所见,您需要注册errorHandler以捕获异常,并phpErrorHandler注册PHP 7 Errors

请注意,两者都不会捕获/warning路由所示的PHP通知。要捕获它,您需要注册自己的错误处理程序:

set_error_handler(function ($severity, $message, $file, $line) {
    if (!(error_reporting() & $severity)) {
        // This error code is not included in error_reporting, so ignore it
        return;
    }
    throw new \ErrorException($message, 0, $severity, $file, $line);
});