全局性配置,用得比较多
1:继承SimpleMappingExceptionResolver
public class CustomSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver {
@Override
protected ModelAndView doResolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
// Expose ModelAndView for chosen error view.
String viewName = determineViewName(ex, request);
if (viewName != null) {// JSP格式返回
if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
.getHeader("X-Requested-With")!= null && request
.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
// 如果不是异步请求
// Apply HTTP status code for error views, if specified.
// Only apply it if we're processing a top-level request.
Integer statusCode = determineStatusCode(request, viewName);
if (statusCode != null) {
applyStatusCodeIfPossible(request, response, statusCode);
}
return getModelAndView(viewName, ex, request);
} else {// JSON格式返回
try {
PrintWriter writer = response.getWriter();
writer.write(ex.getMessage());
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
} else {
return null;
}
}
}
2,在配置文件中webmvc-config.xml,加入异常处理bean
<bean id="exceptionResolver" class="com.xxx.common.exception.CustomSimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.xxx.common.exception.SystemException">500</prop> 其中的500是jsp名 500.jsp
<prop key="com.xxx.common.exception.BusinessException">errorpage</prop> 其中的是jsp名 errorpage.jsp
<prop key="java.lang.exception">500</prop>
</props>
</property>
</bean>
其中BusinessException 为自定义异常类
public class BusinessException extends Exception
3,页面
必须有 isErrorPage="true"
例子:
<%@ page language="java" pageEncoding="UTF-8" isErrorPage="true"%>
<%@ page isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<title>XXX系统</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body style="margin: 0;padding: 0;background-color: #f5f5f5;">
<div id="center-div">
服务器内部错误,请联系系统管理员!!
${exception.message}
</div>
</body>
</html>