系统中异常包括两类:编译时异常和运行时异常,前者通过捕获异常从而获得异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
系统的dao、service、controller出现都通过throws Exception向上抛出,最后由SpringMVC前端控制器交由异常处理器进行异常处理。
package com.llb.exception; /**异常类 * Ceate By llb on 2019/8/21 */ 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; } }
错误页面:
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2019/8/21 Time: 17:37 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <h1>网络去旅行了</h1> ${msg} </body> </html>
package com.llb.exception; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 处理异常业务逻辑 * Ceate By llb on 2019/8/21 */ public class SysExceptionResolve implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object obj, Exception ex) { //获取到异常 SysException e = null; if (ex instanceof SysException){ e = (SysException) ex; }else{ e = new SysException("系统正在维护"); } //创建ModelAndView对象 ModelAndView mv = new ModelAndView(); mv.addObject("msg", e.getMsg()); mv.setViewName("exception"); return mv; } }
springmvc.xml中配置:
<!--配置异常处理器:自定义的异常处理器--> <bean id="sysExceptionResolve" class="com.llb.exception.SysExceptionResolve"></bean>
源码:github
原文:https://www.cnblogs.com/liulebin/p/11393593.html