springmvc异常处理

1.创建一个异常类

/**
* 自定义异常类
*/
public class SysException extends Exception{

//存储提示信息
private String message;

@Override
public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public SysException(String message) {
this.message = message;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2.conteoller控制类

@Controller
@RequestMapping("/user")
public class UserConteoller {

@RequestMapping("/testException")
public String testException() throws SysException {
System.out.println("Exception执行了..");

//模拟异常
try {
int a = 10 / 0;
} catch (Exception e) {
//打印异常信息
e.printStackTrace();
//抛出自定义异常信息
throw new SysException("查询所有用户出现错误...");
}

return "success";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
3.异常处理器类

/**
* 异常处理器
*/
public class SysExceotionResolver implements HandlerExceptionResolver {

/**
* 处理异常的业务逻辑
* @param httpServletRequest
* @param httpServletResponse
* @param
* @param
* @return
*/
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, 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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
4.配置

<!--配置异常处理器-->
<bean id="sysExceotionResolver" class="sise.cn.exception.SysExceotionResolver"></bean>
1
2
5.创建error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>

${errorMsg}
</body>
</html>

原文地址:https://www.cnblogs.com/ly570/p/10983117.html