1.Spring MVC的四种异常处理方式
1.SimpleMappingExceptionResolver
spring-mvc.xml配置:
<!--异常都返回到同一个页面-->
<bean id="simpleMappingExceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArithmeticException">error</prop>
<prop key="java.lang.NullPointerException">error</prop>
</props>
</property>
</bean>
controller:
@Controller
public class ExceptionController {
@GetMapping("/hello")
public void hello() {
int i = 1 / 0;
}
}
error.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>统一错误页面</title>
</head>
<body>
<h1>统一一种处理</h1>
</body>
</html>
这种异常处理方式,有一个问题是没法带数据。
2.HandlerExceptionResolver
handler:
@Component
public class MyGlobalExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
HashMap<String, Object> map = new HashMap<>();
map.put("errorMsg", "全局异常处理");
ModelAndView modelAndView = new ModelAndView("error", map);
return modelAndView;
}
}
error.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="p" uri="http://www.springframework.org/tags" %>
<html>
<head>
<title>统一错误页面</title>
</head>
<body>
<h1>统一一种处理</h1>
<h2>${errorMsg}</h2>
</body>
</html>
这是一种全局异常处理器,我们可以通过ModelAndView来返回异常页面及信息。
3.@ExceptionHandler
handler:
@Controller
public class ExceptionController {
@GetMapping("/hello")
public void hello() {
int i = 1 / 0;
}
@ExceptionHandler(value = {ArithmeticException.class})
public ModelAndView handler(Exception ex) {
ModelAndView view = new ModelAndView("error");
view.addObject("errorMsg", "局部异常处理");
return view;
}
}
error.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="p" uri="http://www.springframework.org/tags" %>
<html>
<head>
<title>统一错误页面</title>
</head>
<body>
<h1>统一一种处理</h1>
<h2>${errorMsg}</h2>
</body>
</html>
这是一个局部异常处理,只对当前的Controller有效。通常在工作中,我们会有统一的Response,那么我们就可以返回一个JSON对象,而不需要使用JSP。这是相对于前两种方式的优势所在。
4.@ExceptionHandler+@ControllerAdvice
controller:
@Controller
public class ExceptionController {
@GetMapping("/hello")
public void hello() {
int i = 1 / 0;
}
}
handler:
@ControllerAdvice
public class MyAnnotationGlobalExceptionHandler {
@ExceptionHandler(value = {RuntimeException.class})
public ModelAndView handler() {
System.out.println("注解全局异常处理,处理所有运行时异常");
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("errorMsg", "注解全局异常处理");
return modelAndView;
}
}
error.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="p" uri="http://www.springframework.org/tags" %>
<html>
<head>
<title>统一错误页面</title>
</head>
<body>
<h1>统一一种处理</h1>
<h2>${errorMsg}</h2>
</body>
</html>
这种方式也是一种全局异常处理,只不过将第二种方式使用了注解来代替。这种方式我们也可以做统一Response返回。