package com.aisino.common.exception;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
/**
* @Description: 自定义处理异常解析器
* @author zhangfei
* @date 2016-10-8 上午9:19:13
* @version V1.0
*/
public class CustomHandlerExceptionResolver implements HandlerExceptionResolver{
private Logger logger = Logger.getLogger(CustomHandlerExceptionResolver.class);
private static Map<String,Long> errorMap = new HashMap<String,Long>();
private static byte [] errorLock = new byte[0];
@Override
public ModelAndView resolveException(HttpServletRequest req,HttpServletResponse resp, Object obj, Exception e) {
//Map<String, Object> model = new HashMap<String, Object>();
//model.put("e", e);
// 除session失效异常外的异常,打印异常信息
if (!(e instanceof SessionFailureException)) {
String className = e.getClass().getSimpleName();
System.out.println("发生了异常"+className);
boolean doLog = false;
Long currentTime = System.currentTimeMillis();
synchronized(errorLock){
Long time = errorMap.get(className);
// 3分钟内 相同异常
if (time != null) {
if (currentTime -time > 170000) {
errorMap.remove(className);
}
}else{
errorMap.put(className, currentTime);
doLog = true;
}
}
if (doLog) {
logger.error("",e);
}
// ajax请求异常
if(req.getHeader("x-requested-with") != null && req.getHeader("x-requested-with").equals("XMLHttpRequest")) {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return new ModelAndView("empty");
}
return new ModelAndView("500");
}
// ajax请求异常
if(req.getHeader("x-requested-with") != null && req.getHeader("x-requested-with").equals("XMLHttpRequest")) {
resp.setHeader("sessionstatus", "timeout");
return new ModelAndView("empty");
}
return new ModelAndView("sessionErr");
}
}
web-servlet.xml
<!-- 自定义异常处理解析器 -->
<bean class="com.aisino.common.exception.CustomHandlerExceptionResolver"/>
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.aisino.common.exception.SessionFailureException">/sessionErr</prop>
<prop key="java.lang.Exception">/500</prop>
<prop key="java.lang.Throwable">/500</prop>
</props>
</property>
<property name="statusCodes">
<props>
<prop key="errors/error">500</prop>
<prop key="errors/404">404</prop>
</props>
</property>
<!-- 设置日志输出级别,不定义则默认不输出警告等错误日志信息 -->
<property name="warnLogCategory" value="WARN"/>
<!-- 默认错误页面,当找不到上面mappings中指定的异常对应视图时,使用本默认配置 -->
<property name="defaultErrorView" value="/500.jsp"/>
<!-- 默认HTTP状态码 -->
<property name="defaultStatusCode" value="500"/>
</bean>