异常处理思路
系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:
springmvc提供全局异常处理器进行统一的异常处理,一个系统只有一个异常处理器
自定义异常类
对不同的异常类型定义异常类,继承Exception。
package com.hrm.error;
/*
* 系统自定义异常类*/
public class CustomException extends Exception{
//异常信息
public String message;
public CustomException(String message){
super(message);
this.message = message;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
全局异常处理器
思路:
系统遇到异常时,在程序中手动抛出,dao抛给service,service再抛给Controller,最后Controller抛给前端控制器,前端控制器调用全局异常处理器
全局异常处理器处理思路:
解析出异常类型,若该异常类型是系统自定义的异常,直接取出异常信息在错误页面展示即可。
如果不是系统自定义异常,构造一个系统自定义的异常类型,信息为“未知错误”
springmvc提供一个HandlerExceptopnResolver
package com.hrm.error;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
// 解析出异常类型
CustomException customException = null;
// 若该异常类型是系统自定义的异常,直接取出异常信息在错误页面展示即可。
if(e instanceof CustomException){
customException = (CustomException)e;
}else{
// 如果不是系统自定义异常,构造一个系统自定义的异常类型,信息为“未知错误”
customException = new CustomException("未知错误");
}
//错误信息
String message = customException.getMessage();
ModelAndView modelAndView = new ModelAndView();
//将错误信息传到页面
modelAndView.addObject("message",message);
//指向错误页面
modelAndView.setViewName("/jsp/error.jsp");
return modelAndView;
}
}
错误页面
<%--
Created by IntelliJ IDEA.
User: 15757
Date: 2019/4/10
Time: 16:38
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>页面出错,请稍后访问</title>
</head>
<body>
${message}
</body>
</html>
springmvc.xml中的配置全局异常处理器
<!-- 配置异常解析器 -->
<bean class="com.hrm.error.CustomExceptionResolver"></bean>