我正在使用Spring MVC 3。
我验证各种用户的输入并显示适用的错误。
但这经常显示在用户界面上显示诸如org.springframework.core.convert.ConversionFailedException
等的spring错误。如何防止这些错误在网页上输出?
最佳答案
Note:
I understand that for topic starter my answer may be no longer relevant. But it can be useful for those who have visited this page to search for solutions to similar problems.
回答:
为了防止在网页上输出错误,您可以进行处理。在Spring MVC 3.x及更高版本中,可以使用几种类型的错误处理:
基于 Controller 的异常处理
您可以在 Controller 内部的方法上添加@ExceptionHandler批注。对于从同一 Controller 中标注为@RequestMapping的方法引发的异常,此类方法将充当错误处理程序。
@ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception e) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", e);
modelAndView.addObject("url", req.getRequestURL());
modelAndView.setViewName("error");
return modelAndView;
}
全局异常处理
Controller 建议使您可以将异常处理应用于整个应用程序,而不仅仅是单个 Controller 。换句话说,处理将应用于从任何 Controller 引发的异常。
@ControllerAdvice
class GlobalControllerExceptionHandler {
public static final String DEFAULT_ERROR_VIEW = "error";
@ExceptionHandler(Exception.class)
public void handleError(HttpServletRequest req, Exception e) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", e);
modelAndView.addObject("url", req.getRequestURL());
modelAndView.setViewName(DEFAULT_ERROR_VIEW);
return modelAndView;
}
}
For more info:
关于spring - 防止网页上出现Spring错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22798693/