views:

42

answers:

1

I currently have this class that another programmer in my team coded:

public static class SoapExecuter
{
    private static readonly ILog logger;

    public static Exception ExecuterException { get; private set; }

    public static bool IsSoapException
    {
        get 
        {
            if (ExecuterException == null)
                return false;

            return ExecuterException.GetType() == typeof(SoapException);
        }
    }

    public static bool Execute(Action action)
    {
        ExecuterException = null;
        bool passed = false;

        try
        {
            action();
            passed = true;
        }
        catch (SoapException se)
        {
            ExecuterException = se;
            logger.log(se);
        }
        catch (Exception ex)
        {
            ExecuterException = ex;  
            logger.log(ex);
        }

        return passed;
    }
}

This is not very idiomatic and I would like to change it to something that happens within the try...catch clause.
Is there a way to not violate DRY and still stay within the idioms the language offers?
Of course I can inherit from the SoapException and log it but I'll have to catch a SoapException and create a new exception object that wraps it and then throw it only to be silenced one level above.
Any idea guys?

+1  A: 

Sounds like what you really want is not to handle that exception inside Execute at all. The responsibility for handling the exception seems to lie with the code that calls Execute.

Of course you can still catch it, store it in ExecuterException, log it, and then rethrow it using throw; — but the purpose of ExecuterException eludes me. It seems that you only need it for IsSoapException, which in turn is much better written as ExecuterException is SoapException anyway, which even takes care of nullness and subclasses.

I don’t think anyone can be of any further help than this without seeing the code that uses the code you posted. If that code queries ExecuterException only immediately after calling Execute, then you can (and should) probably just change it to a try/catch in that code. If it actually queries ExecuterException elsewhere, then you could consider having that code store the reference instead, but either way, it would mean that the code is pretty entangled spaghetti code and probably requires a major rewrite anyway.

(By the way, just to nitpick, the first of the two catch clauses in your code is completely redundant. If you remove it you get exactly the same behaviour — unless logger.log has a special overload for SoapException, but then you should probably restructure that too.)

Timwi
logger.log treats SOAPException in a different way, yes.And the ExecuterException is used only near the executer.execute()
the_drow