【问题标题】:Slim Framework 3 - Response objectSlim Framework 3 - 响应对象
【发布时间】:2017-08-12 13:26:43
【问题描述】:

在我的 Slim 3 应用程序中,我定义了一个中间件,它为我的响应添加了一个自定义标头。 索引路由函数被调用之前调用中间件。如果抛出异常,则会调用错误处理函数,但似乎传递给该函数的 $response 对象是一个新的 Response 对象,而不是在我的中间件中自定义的对象。换句话说,在我的回复中,我没有自定义标题。

这种行为正确吗?

# Middleware
$app->add(function ($request, $response, $next) {
  $response = $response->withHeader('MyCustomHeader', 'MyCustomValue');
  return $next($request, $response);
});

# Error handling
$container['errorHandler'] = function ($container) {
  return function ($request, $response, $exception) use ($container) {
    return $response->write('ERROR');
  };
};

# Index
$app->get('/index', function(Request $request, Response $response) {
  throw new exception();
  return $response->write('OK');
});

【问题讨论】:

    标签: php slim-3


    【解决方案1】:

    是的,它是正确的,因为:

    RequestResponse 对象是不可变的,因此它们需要通过所有函数传递。抛出异常时,这条链被破坏,新创建的 Response 对象(在withHeader-method 上)无法传递给errorHandler。

    您可以通过抛出 \Slim\Exception\SlimException 来解决该问题,此异常需要 2 个参数。请求和响应。有了这个,Slim 使用错误处理程序内部异常中给出的请求和响应。

    $app->get('/index', function(Request $request, Response $response) {
        throw new \Slim\Exception\SlimException($request, $response);
        return $response->write('OK');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 2018-06-18
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多