发布时间:2018-05-01作者:laosun阅读(4265)
jfinal 将exception等异常信息保存到数据库,并且将报错信息美化排版
首先需要给jfinal创建拦截器
public class Exceptionnterceptor implements Interceptor { @Override public void intercept(Invocation ai) { Controller controller = (Controller)ai.getController(); HttpServletRequest request = controller.getRequest(); try { ai.invoke(); return; } catch (Exception e) { e.printStackTrace(); doLog(ai,e); //判断是否ajax请求 String header = request.getHeader("X-Requested-With"); boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header); if(isAjax){ controller.renderJson("0"); }else{ controller.render("/WEB-INF/view/error/500.html"); } }finally{ //TODO } } private void doLog(Invocation ai,Exception e) { //开发模式 if(JFinal.me().getConstants().getDevMode()){ e.printStackTrace(); } //业务异常不记录 if(JfinalUtils.getSwitch(CommonUtils.SettingGlobal.SYSTEM_RUNTIME_LOG_SAVEDB_SWITCH, ai.getController().getSession())){ //系统异常记录开关 TSysLog4j sl = new TSysLog4j(); sl.set("project_id", 1); sl.set("level", "ERROR"); sl.set("controller", ai.getController().getClass().getName()); sl.set("method", ai.getMethodName()); sl.set("type", e.getClass().getName()); sl.set("message", getStackMsg(e)); sl.set("add_time", DateUtils.getDate()); StackTraceElement[] stackArray = e.getStackTrace(); if(stackArray!=null && stackArray.length>0){ StackTraceElement element = stackArray[0]; sl.set("line", element.getLineNumber()); } sl.save(); } if(JfinalUtils.getSwitch(CommonUtils.SettingGlobal.SYSTEM_RUNTIME_LOG_EMAIL_SWITCH, ai.getController().getSession())){ //发送邮件通知 } } /** * 获取格式化堆栈异常信息 * @author sun * @date 2017年5月15日 下午9:16:55 * @param e * @return */ private static String getStackMsg(Exception e) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); return sw.toString() + "\r\n"; } catch (Exception e2) { return "bad getErrorInfoFromException"; } } }
记得在启动config配置文件中增加
public void configInterceptor(Interceptors me) { me.add(new Exceptionnterceptor()); }
看效果图:
详情图:
版权属于: 技术客
原文地址: https://www.sunjs.com/article/detail/a48c945ffb27408d8755e765c50fd39b.html
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。