1

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.

1 Answers1

0

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.

xenoterracide
  • 16,274
  • 24
  • 118
  • 243
  • 1
    Thanks, I know I can do this but that would require me to catch the original exception and wrap/throw my custom exception which I don't want to do because not only does it add more code and clutter up the codebase I want the exception handling to be transparent true to the concept of AOP. I just want to avoid putting in try catch in each and every request handler for all controllers, I feel that defeats the purpose somewhat. – funnyman7878 Oct 05 '15 at 00:27
  • @funnyman7878 I've always felt that throwing domain specific exceptions is better... my 2 cents. You could inject things like the request context, though honestly I don't recall how to do that. You can also make some request scoped objects, and put things into them. – xenoterracide Oct 05 '15 at 04:20
  • Note that the thrown exceptions can stem input parameter validation and will kick in even before you get to your code. – Michael Piefel Feb 09 '17 at 12:53