首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

怎么当freemarker模板出现异常时屏蔽异常并跳转

2012-10-09 
如何当freemarker模板出现错误时屏蔽错误并跳转注意:以下尝试都是使用spring2.5及以上版本在日常的开发过

如何当freemarker模板出现错误时屏蔽错误并跳转
注意:以下尝试都是使用spring2.5及以上版本
   在日常的开发过程中,对错误信息的合理处理都是很重要的一个环节,特别对于门户系统,其重要性就不言而喻了

然而我们在实际的开发过程中,要想错误提示明确、又要想客户不至于太反感,看似矛盾的问题我们怎么处理呢?

  大多数系统都是采用一检测到错误,统一跳转到统一的错误页面,然后统一去做处理,但是那种错误检测仅仅是处理大部分的错误,如java.sql.SQLException、java.lang.RuntimeException,但是对于使用freemarker模板语言的系统来说,其支持不是很好(我尝试把freemarker.template.TemplateException等异常加入到其检测机制中,发现没有作用,只好改用其实现方法)。通过查询freemarker、spring的api获知,freemarker提供了一个支持其错误处理机制的接口TemplateExceptionHandler,需要自己去扩展实现,构造自己的处理freemarker模板错误的机制

主要分为两个部分 1、构造自己的错误处理机制

                                  2、在spring启动的时候将自定义的错误机制加入到freemarker配置中

具体做法如下:

     1、新建一个类,让其实现TemplateExceptionHandler接口

     public class LenovoFreemarkerExceptionHandler implements TemplateExceptionHandler{

      public void handleTemplateException(TemplateException arg0,
       Environment arg1, Writer out) throws TemplateException {
          //这里构建你的错误机制,可以进行跳转及错误日志的打印等等

  }

}

     2、新建一个类,让其继承FreeMarkerConfigurer

  public class LenovoFreemarkerConfigration extends FreeMarkerConfigurer  {
     @Override
    public void afterPropertiesSet() throws IOException, TemplateException {
      if (getConfiguration() == null) {
           setConfiguration(createConfiguration());
      }
      getConfiguration().setTemplateExceptionHandler(new LenovoFreemarkerExceptionHandler());
}
}
1 楼 heqishengcai 2010-09-29   对我有用。既然楼主发现exception handle了,就省的我们再找了。
为了尊敬您的工作,特此留言
对楼主的分享精神表示感谢。

热点排行