一.异常分类:
1.运行时异常 RuntimeException,
2.自定义异常(业务级别)
二.异常的处理:
建立自定义异常类
继承Exception,用于保存异常信息
public class CustomException extends Exception{ private static final long serialVersionUID = -7927745663334155292L; //用于保存异常信息 private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
2.自定义全局异常处理器
public class CustomGlobalExceptionResolver implements HandlerExceptionResolver{
//保存异常信息
private String message = "";
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object arg2, Exception exc) {
if (exc instanceof CustomException) {
//自定义异常
message = ((CustomException)exc).getMessage();
} else {
//运行时异常
message = "对不起,系统异常,请及时联系管理员!";
}
ModelAndView modelAndView = new ModelAndView();
//将错误信息数据放入model中
modelAndView.addObject("message", message);
modelAndView.setViewName("error");
return modelAndView;
}
}
3.配置自定义异常处理器
pringMvc.xml
<bean class="com.test.exception.CustomGlobalExceptionResolver"></bean>
4.定义异常的错误页面