views:

87

answers:

3

I am trying to come up with a manageable way to handle exceptions in a DAO. Typically a method in my DAO looks like this:

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

If an error happens in the above code then everything is written to server.log and on the front page I show custom error screen. However, I want to avoid to put the stacktrace to server.log but instead write it to my_app.log (I'm using log4j).

So I'm planning to transform above method to following:

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
}

Questions:

  • Is this the best way to approach the problem?
  • I have lot of methods in the DAO and doing the above for each method will be a PITA..Is there an easier way to do this so same thing applies to all the methods in a DAO?
+1  A: 

A 'callback' solution in order to handle exception and log in one place:

interface CallBack{
    void invoke();
}

Define a skeleton method like:

//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;
    }
}

Call it like:

public ArrayList fetchColors (String id) throws SqlException{
    doBusiness(new CallBack(){

        public void invoke() {
               //call iBatis SqlMapClient
               //put results in a list     
            }        
    });
}
卢声远 Shengyuan Lu
+4  A: 

I think you can use AOP here. For example:

<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>

Also as a side note you should always log like this so that you can see the stack trace in the log file.

logger.log (e,e);

CoolBeans
+2  A: 

I recommend you add some method logging with Spring AOP. As CoolBeans showed, you can simply use an @AfterThrowing advice.

James Earl Douglas
That's a good link. I will bookmark it.
CoolBeans