SpringMVC之处理异常
1.编写自定义异常类
功能:
做提示信息
public class SysException extends Exception {
/**
* 存储提示信息
*/
private String message;
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SysException(String message, String message1) {
super(message);
this.message = message1;
}
}
2.编写异常处理器
public class SysExceptionResolver implements HandlerExceptionResolver {
/**
* 处理异常的业务逻辑
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @param e
* @return
*/
@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");//error.jsp在 /WEB-INF/pages/ 路径下
return modelAndView;
}
}
3.配置异常处理器
跳转到提示页面
springmvc.xml中
<!--配置异常处理器-->
<bean class="xyz.zhouzhousag.exception.SysExceptionResolver" id="sysExceptionResolver">
</bean>
4.测试Controller
controller
@Controller
@RequestMapping("/user")
public class userControll {
@RequestMapping("/testException")
public String testException() throws SysException {
System.out.println("testException执行了。。。。");
try {
//模拟异常
int i = 1/0;
} catch (Exception e) {
//控制台打印异常信息
e.printStackTrace();
//抛出自定义异常信息
throw new SysException("查询所有用户异常");
}
return "success";
}
}
jsp
<a href="user/testException">异常处理</a>