Your original example:
public virtual List<UserDC> GetAllActiveAgentsByReason(int reasonID)
{
try
{
if (reasonID < 0)
{
throw new ArgumentException("An invalid reasonID was passed.");
}
return accessManagerDAO.GetAllActiveAgentsByReason(reasonID);
}
catch (Exception ex)
{
if (ex is AMSException)
{
throw;
}
else
{
throw new AMSException(ex.Message, ex.InnerException);
}
}
}
The catch
clause can't really be moved out of this method because of the bare throw
, but you could get tricky with delegates:
public virtual List<UserDC> GetAllActiveAgentsByReason(int reasonID)
{
return TryHelper(() =>
{
if (reasonID < 0)
{
throw new ArgumentException("An invalid reasonID was passed.");
}
return accessManagerDAO.GetAllActiveAgentsByReason(reasonID);
});
}
Now the amount of "business" code in that method isn't dwarfed by the error handling code.
The TryHelper
method can be defined like this:
protected T TryHelper<T>(Func<T> action)
{
try
{
return action();
}
catch (Exception ex)
{
if (ex is AMSException)
{
throw;
}
else
{
throw new AMSException(ex.Message, ex.InnerException);
}
}
}
I marked it protected
so that it could go in the base class, but if you don't have a common base class, you can put it wherever and mark it public
so it's accessible and static
so that it's easy to invoke.