Spring——AOP拦截Controller将异常信息抛给浏览器

来源:互联网 发布:websocketserver java 编辑:程序博客网 时间:2024/06/06 05:45

背景

     项目在开发阶段,遇到bug是常事,对于前后端分离的项目来讲,一旦一个功能没走通,我们就需要花费时间去确认是前端出现了问题还是后端报了异常。为了提高这种工作效率,我们采用在开发阶段后端一旦出现异常,就将异常信息抛给浏览器,让开发人员一目了然是后端出了问题,是什么异常,大大提高了开发联调效率。等到项目上线之后就将这个开关关掉,不抛异常给浏览器。

实现方法

     使用spring的AfterReturning注解,建立一个类:AfterReturningAspect

/** * 拦截controller,将异常信息抛给浏览器页面 * @author huan * @date 2017/11/22 */@Aspectpublic class AfterReturningAspect {    private static final Logger logger = LoggerFactory.getLogger(AfterReturningAspect.class);    private final Map clazzMap = new HashMap<String, String>();    public AfterReturningAspect() {        reloadProperties();        //设置定时任务,定时加载属性配置文件        Timer timer = new Timer();        timer.schedule(new TimerTask() {            @Override            public void run() {                reloadProperties();            }        }, 1000, 60000);    }    /**     * 加载配置文件将其中你的key-value保存到clazzMap中     */    private void reloadProperties() {        Properties p = new Properties();        try {            InputStream in = new FileInputStream(this.getClass().getClassLoader().getResource("resource.properties").getFile());            p.load(in);        } catch (IOException e) {            logger.error("[AfterReturningAspect.getProperties()]the method of printing log is error", e.getMessage());        }        Enumeration en = p.propertyNames();        while (en.hasMoreElements()) {            String key = (String) en.nextElement();            String property = p.getProperty(key);            clazzMap.put(key, property);        }    }    /**     * 拦截controller将异信息抛给浏览器     * @param rvt  拦截到的Controller给前端返回的实体     */    @AfterReturning(returning = "rvt",pointcut = "@annotation(* com.zh.test.*.controller.*.*(..))")    public void log(Object rvt){        ItooResult result = (ItooResult)rvt;        if("true".equals(this.clazzMap.get("aop.printexception.enable")) && result.getException() instanceof Exception){            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();            response.reset();            response.setCharacterEncoding("UTF-8");            response.setHeader("Content-Type", "text/plain;charset=UTF-8");            response.setHeader("icop-content-type", "exception");            throw new Exception(result.getException());        }    }}

 项目配置方法

    1.添加一个配置文件放在web层的存放配置文件的包下,配置文件名称为resource.properties,内容为:

#是否将异常信息打印到浏览器页面aop.printexception.enable=true

    2.在web层的spring-mvc.xml中添加配置

<aop:aspectj-autoproxy proxy-target-class="true"/><bean class="com.zh.test.tool.aspect.AfterReturningAspect"/>
   3.controller中使用时,在catch代码块中return时加上参数e。

总结

   线上环境时将resource.properties配置文件中aop.printexception.enable设置为false,开发环境设置为true。
   

原创粉丝点击