SpringMVC目录:
SpringMVC 中的异常处理
异常处理的思路
系统中异常包括两类:预期异常和运行时异常 RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。在进行异常处理时,系统的 dao、service、controller 出现都通过 throws Exception 向上抛出,最后由 springmvc 前端控制器交由异常处理器进行异常处理,如下图:
实现步骤
编写异常类
/**
* @Author: Ly
* @Date: 2020-09-29 17:23
* 自定义异常类
*/
public class SysException extends Exception{
//存储提示信息
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SysException(String message) {
this.message = message;
}
}
编写异常时展示的jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${errorMsg}
</body>
</html>
自定义异常处理器
/**
* @Author: Ly
* @Date: 2020-09-29 17:31
* 异常处理器
*/
public class SysExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
//获取到异常对象
SysException e=null;
if(ex instanceof SysException){
e=(SysException)ex;
}else{
e=new SysException("系统正在维护...");
}
//创建ModelAndView对象
ModelAndView mv=new ModelAndView();
mv.addObject("errorMsg",e.getMessage());
mv.setViewName("error");
return mv;
}
}
在springmvc.xml文件中配置异常处理器
<!--配置异常处理器-->
<bean id="sysExceptionResolver" class="com.ly.exception.SysExceptionResolver"></bean>
编写前端控制器测试异常
/**
* @Author: Ly
* @Date: 2020-09-28 22:26
*/
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("testException")
public String testException() throws Exception{
System.out.println("testException执行了...");
try {
//模拟异常
int a=10/0;
} catch (Exception e) {
//打印异常信息
e.printStackTrace();
//抛出自定义异常信息
throw new SysException("查询所有用户出现的错误...");
}
return "success";
}
}
在前端页面进行测试:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>异常处理</h3>
<a href="user/testException">异常处理</a></br>
</body>
</html>