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.