SpringMVC异常处理的流程:
引用sysExceptionResolver
<!--配置异常处理器-->
<bean id="sysExceptionResolver" class="com.fy.exception.SysExceptionResolver"/>
package com.fy.controller;
import com.fy.exception.SysException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/exc")
public class excController {
@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";
}
}
package com.fy.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 ex
* @return
*/
@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;
}
}
package com.fy.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;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>异常处理</h3>
<a href="exc/testException">testException</a>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${errorMsg}
</body>
</html>
效果截图: