1.自定义异常类与自定义异常处理器
1).自定义异常类
/***自定义异常类继承Exception*/public class SysException extends Exception { private String message; @Override public String getMessage() { return message; } public SysException(String message){ this.message=message; }}
2).自定义异常处理器
/** * 自定义异常处理器实现HandlerExceptionResolver接口 */public class SysExceptionResolve implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { ModelAndView mv = new ModelAndView(); SysException sysException =null; if(e instanceof SysException){ sysException= (SysException) e; }else { sysException = new SysException("服务器进入二次元了"); } mv.addObject("message",sysException.getMessage()); mv.setViewName("error"); return mv; }}
2.配置自定义异常处理器和编写error友好界面
1). 在resources目录下的xml文件中配置bean
2).编写error友好界面
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>异常界面 ${message}
3.测试结果
测试结果的前台代码
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>Hello World!
Exception测试
测试结果的后台代码
@Controller@RequestMapping("/user")public class UserController { @RequestMapping("/exception") public String testException() throws SysException { System.out.println("testException..."); try { int a = 10/0; } catch (Exception e) { e.printStackTrace(); throw new SysException("查询数据出错了"); } return "success"; }}