2017-08-12 7 views
1

私のスリム3アプリケーションでは、自分のレスポンスにカスタムヘッダを追加するミドルウェアを定義しました。ミドルウェアは、インデックスルーティング機能が呼び出される前にと呼ばれます。例外がスローされた場合、エラーハンドラ関数が呼び出されますが、その関数に渡される$ responseオブジェクトは、新しいレスポンスオブジェクトであり、ミドルウェアでカスタマイズされたものではありません。言い換えれば、私の応答で私はカスタムヘッダーを持っていません。スリムフレームワーク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'); 
}); 
関連する問題