springMVC异常处理总结
直接上手记录一下总结吧:
模拟异常的java后台:
@RequestMapping("/testException")
public String testException()throws Exception{
System.out.println("testException方法执行了。。。");
//模拟异常
try {
int a = 10/0;
} catch (Exception e) {
e.printStackTrace();
throw new SysException("查询用户出现错误...");
}
return "success";
}
异常类:
public class SysException extends Exception {
//存储提示信息
private String message;
public SysException(String message) {
this.message = message;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
异常处理器类:
public class SysExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
SysException sysException = null;
if (e instanceof SysException){
sysException = (SysException) e;
}else {
sysException = new SysException("系统正在维护...");
}
//创建ModelAndView对象
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("errorMsg",sysException.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
配置异常处理器:
视图解析器:
跳转页面:
还没有评论,来说两句吧...