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?
Sounds like what you really want is not to handle that exception inside
Executeat all. The responsibility for handling the exception seems to lie with the code that callsExecute.Of course you can still catch it, store it in
ExecuterException, log it, and then rethrow it usingthrow;— but the purpose ofExecuterExceptioneludes me. It seems that you only need it forIsSoapException, which in turn is much better written asExecuterException is SoapExceptionanyway, 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
ExecuterExceptiononly immediately after callingExecute, then you can (and should) probably just change it to a try/catch in that code. If it actually queriesExecuterExceptionelsewhere, 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.loghas a special overload forSoapException, but then you should probably restructure that too.)