1.编写自定义异常
public class SysException extends Exception {
private String msg;
public SysException(String msg) {
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
2.控制器模拟异常发生
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testException")
public String testException() throws SysException {
System.out.println("testException执行了");
try {
int a = 10 / 0;
} catch (Exception e) {
// e.printStackTrace();
throw new SysException("查询所有用户出错");
}
return "success";
}
}
3.自定义异常处理器
public class SysExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
//获取异常
SysException exception = null;
if (e instanceof SysException) {
exception = (SysException) e;
} else {
exception = new SysException("系统正在维护。。。");
}
//创建ModelAndView对象
ModelAndView mv = new ModelAndView();
mv.addObject("errorMsg", exception.getMsg());
System.out.println(exception.getMsg());
mv.setViewName("error");
return mv;
}
}
4.在springmvc的配置文件中配置异常处理器
<bean id="sysExceptionResolver" class="com.hhd.exception.SysExceptionResolver"/>