Design Tips: Allow Consumers To Handle Exceptions

I ran into a piece of code where it implemented a kind of retry pattern. It will retry a call if an exception is thrown from the first call. A simple version looks like (not a production or real code).

One of a problem with the above code is that when the first timeout exception occurs, the consumer cannot see it anywhere. At least, the ServiceCallHelper should give consumers a chance to deal with exceptions.

How do we do that with less impact on the design? We should strive for a solution which does not introduce a new dependency. I have seen a tendency of injecting a Logger. I might, and will, work. However, now you have dependency on the logger. And the consumer has to know about that logger.

Now take a look at the new version that I propose

With that simple change, we have introduced an extension point that consumers will be happy. And we ensure that our API does not hide away exceptions.

If you are designing an API, consider your extension points, and whether the API allows consumers to have a chance to be aware of exceptions.

.NET framework comes with powerful built classes Func and Action. Take advantages of the two might help you simplified your design.

Write a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.