Exceptions – Understanding ‘What Happened’ vs ‘What to Do’

exceptions

We use exceptions to let the consumer of the code handle unexpected behaviour in a useful way. Usually exceptions are built around "what happened" scenario – like FileNotFound (we were unable to find file you specified) or ZeroDivisionError (we can divide by 0).

What if there is a need to specify the expected behaviour of the consumer?

For example, imagine we have fetch resource, which performs HTTP request and returns retrieved data. And instead of errors like ServiceTemporaryUnavailable or RateLimitExceeded we would just raise a RetryableError suggesting that the consumer should just retry the request and forget about specific failure. So, we are basically suggesting an action to the caller – the "what to do".

We do not do this often because we don't know all the consumers' usecases. But imagine that in some specific component we do know the best course of actions for a caller – so should we then make use of "what to do" approach?

Best Answer

But imagine that is some specific component we do know the best course of actions for a caller.

This almost always fails for at least one of your callers, for which this behaviour is incredibly irritating. Don't assume you know best. Tell your users what's happening, not what you assume they should do about it. In many cases it's already clear what a sane course of action should be (and, if it's not, make a suggestion in your user manual).

For example, even the exceptions given in your question demonstrate your broken assumption: a ServiceTemporaryUnavailable equates to "try again later", and RateLimitExceeded equates to "woah there chill out, maybe adjust your timer parameters, and try again in a few minutes". But the user may as well want to raise some sort of alarm on ServiceTemporaryUnavailable (which indicates a server problem), and not for RateLimitExceeded (which doesn't).

Give them the choice.

Related Topic