Spring MVC异常统一处理

package com.shzq.common.exception;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.alibaba.fastjson.JSONObject;
import com.shzq.common.utils.ResultUtils;


/**
*Exception 捕获类 把相关Exception写入到日志文件中
* */
public class ExceptionHandler extends SimpleMappingExceptionResolver {

private static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

try {
HashMap<String, Object> resultMap = ResultUtils.error("404", "系统异常,请联系相关人员!");
JSONObject resultObj = new JSONObject(resultMap);

response.setContentType("text/json; charset=utf-8");
response.getWriter().write(resultObj.toJSONString());
//将异常栈信息记录到日志中
logger.error(getTrace(ex));
response.getWriter().flush();
} catch ( Exception e ) {

e.printStackTrace();
}

return null;

}

public static String getTrace(Throwable t) {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
t.printStackTrace(writer);
StringBuffer buffer= stringWriter.getBuffer();
return buffer.toString();
}
}

 

 <bean id="exceptionHandler" class="com.shzq.common.exception.ExceptionHandler"/>  applicationcontext.xml配置 或者是@Component

springmvc 最主要的 是实现 HandlerExceptionResolver 接口

posted @ 2017-03-15 16:12  随风而逝,只是飘零  阅读(268)  评论(0编辑  收藏  举报