2

In the easiest, most straightforward way, how do I wire up a/the ModelAndViewDefiningException doodad to send errors to my specified view?

This guy should be called from: org.springframework.web.servlet.ModelAndViewDefiningException

Much thanks to anyone in advance!

stackoverflow
  • 18,348
  • 50
  • 129
  • 196

1 Answers1

2

How do I wire up ModelAndViewDefiningException to send errors to my view?

It's an exception. You throw it!

The ModelAndViewDefiningException is an exception wrapper for a ModelAndView. The Spring framework recognizes it, catches it, extracts the model and view name from it and forwards to the resolved view exposing the model to the view.

...
if (someBadThingy) {
  ModelAndView modelAndView = new ModelAndView("errorView"); // "errorView" name resolved to a view by the ViewResolver of your app
  throw new ModelAndViewDefiningException(modelAndView);
}
...

You can throw it at any time during handler processing. Normally, inside a Controller's code you don't usually throw the exception because Controller request handler methods return a ModelAndView. So instead of throwing an exception with the ModelAndView inside, you can just return the ModelAndView.

But there are situations when you can't return a ModelAndView. Interceptors are a good example of this because their methods are of void or boolean return. If some condition isn't met inside the interceptor the ModelAndViewDefiningException allows you to break the flow and go to the error view.