首页 > 解决方案 > 捕获异常时的请求状态

问题描述

我有一个带有自定义 errorHandler 的 Slim Framework 应用程序和一个小的中间件堆栈。我的中间件向 Request 对象添加了属性,我希望在发生异常时可以从我的错误处理程序中访问这些属性。例如:

$app->get('/endpoint', function($request $response, $args) {
    $myAttribute = $request->getAttribute('myAttribute'); //returns 'myValue'
    throw new \Exception(); //any code that throws an error
})->add(function($request, $response, $next) {
    $request = $request->withAttribute('myAttribute', 'myValue');
    $response = $next($request, $response);
    return $response;
});

$app->getContainer['errorHandler'] = function($c) {
    return function($request, $response, $exception) {
        $myAttribute = $request->getAttribute('myAttribute'); //returns null
        return $response;
    }
};

该属性在错误处理程序内的 Request 对象中不存在,因为从路由内部克隆的 Request 在遍历中间件堆栈后尚未返回。是否可以在抛出异常时(在该位置)访问 Request 和 Response 对象?我无法显式传递它们(例如,SlimException),因为我也在尝试处理意外错误。

标签: phpslim

解决方案


升级到 Slim 4(如果可以的话)

值得注意的是,Slim 4 解决了这个问题。就个人而言,升级是一种痛苦,因为发生了很多变化,尤其是依赖注入容器(我从 Slim v3.12=>开始4.8)。

在 Slim 4 中,他们将路由和错误处理都移到了(单独的)中间件中。


推荐阅读