Search code examples
javaspringexceptionibatisdao

manageable way to handle exceptions in java


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?

Solution

  • 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     
                }        
        });
    }