Wednesday, October 21, 2015

Who Consumes Exceptions

One thing I see all the time is custom exceptions. Another thing I see is people throwing custom exceptions instead of a naturally occuring exception. For example you might see:

if (foo == null) throw new MyCustomException("Boom");
var thing = foo.bar;

This code is potentially very stupid. Why did I say potentially? It has to do with what happens to an exception. 

When I write a document, any document, my first question is "who is this for?" Who is going to read this thing? How you write a document depends on how it is going to be used. The same is true for exceptions. How are they going to be used? Okay, I will say that they are going to be examined by either programmers or by troubleshooters who are trying to configure a system. 

Now I will divide the programmers into two groups. One is programmers who work on the code and the other is programmers who consume your API. So these are the three audiences for your exceptions. Let's think about what they really want.

Troubleshooters

The most helpful error messages are the ones telling you what to do when you get them. If you throw an error and you can identify some problem in your system then you should try to give a detailed message about what can me done to fix the problem. For example, if you fail to communicate with some external system then throw a message saying so and including the connection information you are using.

API Consumers

If you are writing an API (and most programmers aren't) then you should do the same thing as for troubleshoorters. If you know about an exception then you should give the API user enough details to solve the problem without having to dig into the API code.

Programmers

This is the most common case. A programmer who maintains the code almost always wants to see the raw exception. Adding custom exception classes is almost always bad because they rarely help a programmer find the problem and they just add another level of indirection to be traversed.

Advice

When you throw an exception or create a custom exception think carefully about how this will be helpful to someone. Note that it will rarely be helpful to other programmers, but could prove valuable to those troubleshooting configurations. If you are fuzzy about whether it will be helpful, then consider either not throwing the exception or at least not creating a custom exception.

No comments:

Post a Comment