【问题标题】:manageable way to handle exceptions in java在java中处理异常的可管理方式
【发布时间】:2010-08-23 02:31:18
【问题描述】:

我正在尝试提出一种可管理的方式来处理 DAO 中的异常。通常,我的 DAO 中的方法如下所示:

public ArrayList fetchColors (String id)
{
    //call iBatis SqlMapClient
    //put results in a list
    //return list
}

如果上述代码中发生错误,则所有内容都会写入server.log,并且在首页上我会显示自定义错误屏幕。但是,我想避免将堆栈跟踪放到 server.log 中,而是将其写入my_app.log(我正在使用 log4j)。

所以我打算将上述方法转换为以下方法:

public ArrayList fetchColors (String id) throws SqlException
{
    try {
    //call iBatis SqlMapClient
    //put results in a list
    }
    catch (SqlException e)
    {
      logger.log (e);
      throws e;
    }
    //return list
}

问题:

  • 这是解决问题的最佳方法吗?
  • 我在 DAO 中有很多方法,对每种方法执行上述操作将是一个 PITA。是否有更简单的方法可以做到这一点,因此同样的事情适用于 DAO 中的所有方法?

【问题讨论】:

  • 在我看来这是最好的方法。 Java 只是一种非常冗长的语言。

标签: java spring exception ibatis dao


【解决方案1】:

我认为你可以在这里使用 AOP。例如:

<bean id="exceptionLogger" class="my.good.ExceptionLogger" />  
<aop:config>
        <aop:pointcut id="allDaoMethods" expression="execution(* my.dao.*(..))" />

        <aop:aspect id="daoLogger" ref="exceptionLogger">
            <aop:after-throwing pointcut-ref="allDaoMethods"
                                method="logIt"
                                throwing="e"/>
        </aop:aspect>  
    </aop:config>

另外作为旁注,您应该始终这样记录,以便您可以在日志文件中看到堆栈跟踪。

logger.log (e,e);

【讨论】:

    【解决方案2】:

    一种“回调”解决方案,用于处理异常并在一个地方登录:

    interface CallBack{
        void invoke();
    }
    

    定义一个骨架方法,如:

    //Skeleton to handle exception and log in one place 
    public void doBusiness(CallBack callBack)  throws SqlException{
        try{
            callBack.invoke();
        }catch(SqlExceptione){
            logger.log (e);
            throws e;
        }
    }
    

    这样称呼:

    public ArrayList fetchColors (String id) throws SqlException{
        doBusiness(new CallBack(){
    
            public void invoke() {
                   //call iBatis SqlMapClient
                   //put results in a list     
                }        
        });
    }
    

    【讨论】:

      【解决方案3】:

      我建议你添加一些method logging with Spring AOP。正如 CoolBeans 所示,您可以简单地使用 @AfterThrowing 建议。

      【讨论】:

        猜你喜欢
        • 2015-05-21
        • 2011-09-26
        • 1970-01-01
        • 2015-02-19
        • 2015-09-16
        • 1970-01-01
        • 2013-09-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多