简体   繁体   中英

Spring MVC ExceptionHandler and the controller context

This should be a common problem with a solution but I haven't managed to find it anywhere.

I am defining a global exception handler using @ControllerAdvice, I define a new ModelAndView and redirect to my error page. Works great EXCEPT for the fact that now we want to add a link to go back to the original page which of course could vary depending on where the error originated.

What I want to do is to store some kind of context information about the controller that generated the error, for instance if it's MyController then I can access a value via MyController.EXCEPTION_REDIRECT_URL and generate the appropriate link.

I find a lack of context information in the Exception handler rather limiting.

Make a custom exception class and pass your context in the exeption.

class MyException extends Exception {
  private MyController c;
  MyException( String msg, MyController c ) {...}
  ...
}

I do feel like there's a better way, probably revolving around a request context object. But this would do exactly what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM