How to handle exceptions in a layered application?

Technology CommunityCategory: Layering & MiddlewareHow to handle exceptions in a layered application?
VietMX Staff asked 5 months ago

I would stick with two basic rules: 1. Only catch exceptions that you can handle to rescue the situation. That means that you should only catch exceptions if you, by handling it, can let the application continue as (almost) expected. 2. Do not let layer specific exceptions propagate up the call stack. create a more generic exception such as LayerException which would contain some context such as which function failed (and with which parameters) and why. I would also include the original exception as an inner exception.

Consider:

public class UserRepository : IUserRepository
{
    public IList<User> Search(string value)
    {
        try
        {
              return CreateConnectionAndACommandAndReturnAList("WHERE value=@value", Parameter.New("value", value));
        }
        catch (SqlException err)
        {
             var msg = String.Format("Ohh no!  Failed to search after users with '{0}' as search string", value);
             throw new DataSourceException(msg, err);
        }
    }
}