php - 捕获异常时的请求状态
问题描述
我有一个带有自定义 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),因为我也在尝试处理意外错误。
解决方案
升级到 Slim 4(如果可以的话)
值得注意的是,Slim 4 解决了这个问题。就个人而言,升级是一种痛苦,因为发生了很多变化,尤其是依赖注入容器(我从 Slim v3.12
=>开始4.8
)。
在 Slim 4 中,他们将路由和错误处理都移到了(单独的)中间件中。
推荐阅读
- python - 如何平衡 GAN 中的生成器和判别器性能?
- delphi - Delphi:在 TWebBrowser 中显示 PDF
- javascript - 根据是否支持全屏以及是否已处于全屏模式显示文本
- url - cURL 包装 url 包含具有正斜杠的令牌
- java - JAVA - 得到空的 MockHttpServletResponse:body..但是它是 200
- postgresql - 如何禁用唯一键
- python - 容器连接被拒绝
- c# - Azure 持久函数日志
- angular - 角度传递参数到调用函数
- laravel - 使用带有 x-api-key 令牌的 Laravel HTTP 客户端