2017-08-12 83 views
1

在我的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'); 
}); 

回答

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'); 
});