我正在尝试设置一个方案来统一处理Spring中的异常。因此,我需要一种方法将上下文信息传递到@ExceptionHandler
- 带注释的方法,例如考虑以下内容:
@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();
}
由于Spring负责将抛出的异常转换为handleException()
的调用,因此我很难找到将myContext
传递给处理程序的方法。我有一个想法是创建一个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();
}
但是,如果我遵循这种方法,我如何正确使用我自己的任意子类HttpServletRequest来使其工作?
答案 0 :(得分:1)
难道你不能把它放到异常中(如果需要的话 - 用新的异常包装原始异常)?
@ExceptionHandler(MyContextualException.class)
public void handleException(MyContextualException ex) {
// 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"
...
try {
i_will_always_throw_an_exception();
} catch (Exception ex) {
throw new MyContextualException(myContext, ex);
}
}
另一种方法是将上下文作为请求属性传递:
request.setAttribute("myContext", myContext);