1
Springで例外を一様に処理するための体系を設定しようとしています。そのように、私は次のことを考慮して、たとえば、@ExceptionHandler
-annotated方法にコンテキスト情報を渡す方法が必要になります。Spring 3.0例外ハンドラでのコンテキスト情報の取得
@ExceptionHandler(Exception.class)
public void handleException(Exception ex, HttpServletRequest request) {
// Need access to myContext from login()
}
@RequestMapping(value = "{version}/login", method = RequestMethod.POST)
public void login(HttpServletRequest request, @PathVariable String version, @RequestParam("userName") String userName, @RequestParam("password") String password, ModelMap model) throws Exception {
...
myContext = "Some contextual information"
...
i_will_always_throw_an_exception();
}
春はhandleException()
の呼び出しにスローされた例外を翻訳する責任があるので、私は難しさを持っていますハンドラにmyContext
を渡す方法を見つけようとしています。私が持っている考えの1つは、HttpServletRequestのサブクラスを作成することです。私はこのアプローチに従うならば、どのように私は適切にこの作品を作るためのHttpServletRequestの私自身の任意のサブクラスを使用しない、
@ExceptionHandler(Exception.class)
public void handleException(Exception ex, MyCustomHttpServletRequest request) {
// I now have access to the context via the following
String myContext = request.getContext();
}
@RequestMapping(value = "{version}/login", method = RequestMethod.POST)
public void login(MyCustomHttpServletRequest request, @PathVariable String version, @RequestParam("userName") String userName, @RequestParam("password") String password, ModelMap model) throws Exception {
...
myContext = "Some contextual information"
request.setContext(myContext);
...
i_will_always_throw_an_exception();
}
しかし:そのアプローチが機能する場合、私はこのようなコードを持っているでしょうか?
はい、これは、@ exceptionHandlerの注釈付きメソッドの利便性を持つことの目的を打ち負かすようだ:
別のアプローチは、リクエスト属性としてコンテキストを渡すことです。私は基本的に大量のtry-catchブロックを持つ@ RequestMappingアノテートメソッドの束を避けたい。 Springのドキュメントでは、上記のlogin()メソッドは複数のタイプのHttpServletRequestsを受け入れることができると示唆していますが、* how *を行うためのドキュメントはまだ見つかりません。 –
コンテキストとして属性を設定することはおそらくOKですが特に優雅ではないが、そのトリックを行う必要があります。 –
+1を使用してrequest.setAttribute – sourcedelica