首先看一个异常页面
404/500可能是大家最熟悉的两个错误代码,在传统方式下,代码遇到类如1/0这样的异常时,我们可以用try-catch捕获,交给前端控制器处理,如果前端控制器没有规范好异常处理器来处理这些异常,则会交由浏览器处理,也就出现了上图所看到的那样。
这个页面对于开发人员也还好,一眼就能看到问题出哪儿了。可是,对于操作人员而言,则显得不是那么友好了。
所以,可以定义一个异常处理器,分门别类的把多方面的异常进行补货,跳转到对应的错误信息页面,同时可以提示操作者一些错误信息。
下面,我们模拟一个查询所有用户的请求,在控制器中加入1/0
这样一段错误代码,让程序进行异常处理。
- 自定义个Exception子类,提供有参构造。
public class SystemException extends Exception{
private String message;
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SystemException(String message) {
this.message = message;
}
}
- 实现HandlerExceptionResolver接口,自定义异常处理器。
参数中的Exception e
为我们代码中补货到的异常;如果有多个类似SystemException
这样的异常,我们需要多个判断语句;ModelAndView
的setViewName
方法指定返回页面,视图解析器会自动拼接前缀后缀指向实际的页面地址。
public class SystemExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
Exception ex;
ModelAndView mv;
if(e instanceof SystemException){
ex = (SystemException)e;
}else{
ex = new Exception("未知异常!");
}
mv = new ModelAndView();
mv.addObject("errorMsg",ex.getMessage());
mv.setViewName("error");
return mv;
}
}
- 配置异常处理器
在springmvc.xml中配置异常处理器。
<bean id="systemExceptionHandler" class="com.wuwl.exception.handler.SystemExceptionHandler"></bean>
- 编写Controller控制器
@RequestMapping("getAll")
public String getAll() throws SystemException {
try {
int i = 1 / 0;
return "user/userList";
}catch (Exception e){
throw new SystemException("查询用户信息是出现异常:"+ e.getMessage());
}
}
- 编写错误页面
这里整的比较简单,美工可以后续优化;这里需要注意的是isELIgnored="false"
属性别丢。
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<p>系统异常!</p>
<p>异常信息为:${errorMsg}</p>
</body>
</html>
- 测试
点击获取用户列表的连接后,在控制器中捕获异常,交给异常处理器,异常处理器转向错误信息界面,并反馈错误信息。