Skip to content

Instantly share code, notes, and snippets.

@jdiamond
Last active December 16, 2015 15:29
Show Gist options
  • Save jdiamond/5456697 to your computer and use it in GitHub Desktop.
Save jdiamond/5456697 to your computer and use it in GitHub Desktop.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment