版权声明:@AaronFo https://blog.csdn.net/sinat_33212645/article/details/85143744
目录
1.使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver
2.实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器
1.使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver
1.1 在springmvc配置中配置:
<!-- 总错误处理-->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView">
<value>/error/error</value>
</property>
<property name="defaultStatusCode">
<value>500</value>
</property>
<property name="warnLogCategory">
<value>org.springframework.web.servlet.handler.SimpleMappingExceptionResolver</value>
</property>
</bean>
[xml] view plaincopy
<!-- 总错误处理-->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView">
<value>/error/error</value>
</property>
<property name="defaultStatusCode">
<value>500</value>
</property>
<property name="warnLogCategory">
<value>org.springframework.web.servlet.handler.SimpleMappingExceptionResolver</value>
</property>
</bean>
1.2 显示错误的jsp页面:
<%@ page language="java" contentType="text/html; charset=GBK"
pageEncoding="GBK"%>
<%@ page import="java.lang.Exception"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>错误页面</title>
</head>
<body>
<h1>出错了</h1>
<%
Exception e = (Exception)request.getAttribute("exception");
out.print(e.getMessage());
%>
</body>
</html>
[html] view plaincopy
<%@ page language="java" contentType="text/html; charset=GBK"
pageEncoding="GBK"%>
<%@ page import="java.lang.Exception"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>错误页面</title>
</head>
<body>
<h1>出错了</h1>
<%
Exception e = (Exception)request.getAttribute("exception");
out.print(e.getMessage());
%>
</body>
</html>
2.实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器
@Component
public class ExceptionTest implements HandlerExceptionResolver{
/**
* TODO 简单描述该方法的实现功能(可选).
* @see org.springframework.web.servlet.HandlerExceptionResolver#resolveException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
*/
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
System.out.println("This is exception handler method!");
return null;
}
}
3.使用@ExceptionHandler注解实现异常处理
@Controller
public class GlobalController {
/**
* 用于处理异常的
* @return
*/
@ExceptionHandler({MyException.class})
public String exception(MyException e) {
System.out.println(e.getMessage());
e.printStackTrace();
return "exception";
}
@RequestMapping("test")
public void test() {
throw new MyException("出错了!");
}
}