用拦截器截获异常并打印日志


创建一个类MyInterceptor继承Springmvc框架的接口(HandlerInterceptor)

配置SpringMVC的xml文件



//需要拦截的控制器


在MyInterceptor中

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("afterCompletion");
logger.error(getTrace(ex));

}

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();
}