先来个自定义异常
public class CustomException extends Exception {
//异常信息
public String message;
public CustomException(String message){
super(message);
this.message=message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
定义全局异常处理类需要实现HandlerExceptionResolver接口:
public class CustomExceptionResolve implements HandlerExceptionResolver {
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
CustomException customException=null;
if(ex instanceof CustomException){
customException = (CustomException)ex;
}else{
customException=new CustomException("未知错误");
}
ModelAndView mv = new ModelAndView("error");
mv.addObject("error", customException.getMessage());
return mv;
}
}
写一个显示异常信息的页面然后就是springmvc配置文件中声明一下全局异常处理类:
最后就是测试了:
@RequestMapping("testException1")
public void testException1() throws CustomException{
try {
int i =1/0;
} catch (Exception e) {
throw new CustomException("程序出现问题了");
}
}
@RequestMapping("testException2")
public void testException2(){
int i =1/0;
}
结果如下: