I am attempting to set-up a scheme for uniformly handling exceptions in Spring. As such, I need a way to pass context information into an @ExceptionHandler-annotated method, for example consider the following:
@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();
}
Since Spring is responsible for translating a thrown exception into an invocation of handleException(), I am having difficulty trying to find a way to pass myContext to the handler. One thought I have is creating a subclass of HttpServletRequest. If that approach works I would have code like this:
@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();
}
But, if I follow this approach, how do I properly use my own arbitrary sub-class of HttpServletRequest to make this work?
Can’t you just put it into exception (if necessary – wrapping the original exception with the new one)?
An alternative approach is to pass the context as a request attribute: