Slim Framework 3 - 响应对象
问题描述:
在我的Slim 3应用程序中,我定义了一个中间件,它为我的响应添加了一个自定义标头。在索引路由功能被调用之前,中间件被称为。如果抛出异常,则会调用错误处理函数,但似乎传递给该函数的$ response对象是一个新的Response对象,而不是在我的中间件中定制的对象。换句话说,在我的回应中,我没有自定义标题。Slim Framework 3 - 响应对象
此行为是否正确?
# 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');
});
答
是的,它是正确的,这是因为:
的Request
和Response
对象是不可改变的,因此他们需要通过所有的功能进行传递。当抛出一个异常时,这条链被破坏,新创建的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');
});