gpt4 book ai didi

java - 在 Spring 3.0 异常处理程序中获取上下文信息

转载 作者:太空宇宙 更新时间:2023-11-04 08:32:54 25 4
gpt4 key购买 nike

我正在尝试建立一个在 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 的任意子类来完成这项工作?

最佳答案

你不能将其放入异常中(如果需要的话 - 用新异常包装原始异常)吗?

@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);

关于java - 在 Spring 3.0 异常处理程序中获取上下文信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7100104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com