SpringMVC 的异常处理
Controller调用service,service调用dao,异常都是向上抛出的,最终有DispatcherServlet找异常处理器进行一场的处理
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>异常处理</h3>
<a href="user/testException">异常处理</a>
</body>
</html>
自定义异常类
package com.wl.exception;
/**
* 自定义异常类
*/
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;
}
}
异常处理器
package com.wl.exception;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 异常处理器
*/
public class SysExceptionResolver implements HandlerExceptionResolver {
/**
* 处理异常业务逻辑
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @param e
* @return
*/
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
//获取到异常对象
SysException ex = null;
if (ex instanceof SysException) {
e = (SysException) ex;
} else {
e = new SysException("系统正在维护...");
}
ModelAndView mv = new ModelAndView();
mv.addObject("errorMsg", e.getMessage());
mv.setViewName("error");
return mv;
}
}
Controller
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testException")
public String testException() throws SysException{
System.out.println("testException执行了");
try {
//模拟异常
int a = 10/0;
} catch (Exception e) {
e.printStackTrace();
//抛出自定义异常信息
throw new SysException("查询所有的用户出现的错误...");
}
return "success";
}
}
web.xml
<!--配置异常处理器-->
<bean id="sysExceptionResolver" class="com.wl.exception.SysExceptionResolver"/>
error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${errorMsg}
</body>
</html>