Saturday, March 3, 2012

Exceptions are Truly Exceptional

Exceptions are meant to break way from the current workflow and inform the user that some unexpected happened. It is not meant to control the workflow the system. Too often I have seen code like this:

public class Service
{
    public IEnumerable<Entity> GetEntities()
    {
        try
        {
            var entities = repository.GetEntities("select * from table …");
            return entities;
        }
        catch (Exception e)
        {
            Logger.Log(e);
            return new Entity[0];
        }
    }
}

The problem is there is no difference between the repository simply not containing any entities and something going horribly wrong in the lower components. Handling the scenario were no entities are present in the repository is completely different than getting a SQL exception, or any exception for that matter.

In other words, if the database returns no entities, I may want to redirect the user to “add new” screen rather than display an a listing of not entities. However, if an exception was thrown I may want to inform the user something unexpected occurred, that the system administrators have been notified and they should log off of the system, until further notice.

However I cannot do that in this scenario because the calling code cannot distinguish between no entities and fatal operations.

This also means the developer must understand the result have potentially 2 meanings. 1. No data is present and 2. an exception may have occurred.

So how can we improve upon this code so we can return the expected results and still provide a positive user experience within the application itself? That will be the context for my next post.

No comments:

Post a Comment