I am trying to create a controller which can handle all exceptions using springs controller advice annotation.
Below is the class i created for this.
@EnableWebMvc
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
private static final Logger LOGGER = Logger.getLogger(GlobalDefaultExceptionHandler.class);
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
LOGGER.debug("Handling Exception!");
return new ModelAndView(new CustomError("<Error Message>"));
}
}
The method defaultErrorHandler is being called when any unhandled exception is thrown, but it seems to return a 404 error to the browser instead of returning the view CustomError. Anyone have an idea why this could be?
The CustomError class is below
public class CustomError {
private String errorMessage;
public CustomError(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
Thanks.
It seems that you've used the wrong ModelAndView, the class you've used seems to be org.springframework.web.portlet.ModelAndView
wich has the constcutor ModelAndView(java.lang.Object)
the class org.springframework.web.servlet.ModelAndView
which you should have used doesn't have a constructor that accepts Object.
Change the imports and the code accordingly and you should be fine
I think that, there is Runtime exception, which could not be handled by
@ExceptionHandler(value = Exception.class)
.
Please post your controller method as well.
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.