Slim Framework 3 - 响应 object
Slim Framework 3 - Response object
在我的 Slim 3 应用程序中,我定义了一个中间件,它向我的响应添加了自定义 header。调用中间件 before 索引路由函数被调用。如果抛出异常,则会调用错误处理函数,但传递给该函数的 $response object 似乎是一个新的 Response object 而不是我的中间件中自定义的那个。换句话说,在我的回复中,我没有自定义 header.
这种行为是否正确?
# 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');
});
在我的 Slim 3 应用程序中,我定义了一个中间件,它向我的响应添加了自定义 header。调用中间件 before 索引路由函数被调用。如果抛出异常,则会调用错误处理函数,但传递给该函数的 $response object 似乎是一个新的 Response object 而不是我的中间件中自定义的那个。换句话说,在我的回复中,我没有自定义 header.
这种行为是否正确?
# 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');
});