I am building a .NET client library for a public web API. One of the things I'm struggling with is how best to indicate error conditions to a user of the library. Obviously my library should throw or pass exceptions to the caller when there's an execution failure, but should I use existing exceptions or create new exceptions for my library? If I create new exceptions, should I create just one exception or multiple?
Option 1: Use existing exceptions exclusively
At its most basic, I could just for example throw new Exception("API authentication error.");
but this is very generic and would require a lot of processing to deal with afterwards. I could also use more appropriate existing exception like System.Security.Authentication.AuthenticationException
, but then using the library will be awkward because of all the different namespaces. There will be some cases where there is nothing more appropriate than InvalidOprationException
, so it seems that taking this approach will make it cumbersome for whoever is using the library to process errors. The simplest would probably be to just use the HttpException
class, since most error conditions are in any case a translation of HTTP status codes and messages.
Option 2: Create an exception for each situation
I could also create an exception for each scenario, but keep them all within the library. So I could create a NotFoundException
, AuthorizationException
, TransactionsPendingException
and other specific exceptions.
Option 3: Create a single exception for my client
The third option would be to create a single custom exception MyApiException
which contains a status code for the different errors that come up (and an appropriate message, of course). So I might then throw new MyApiException(401,"Not authorized.")
It seems to me that option 3 is the most straightforward to implement and easiest for the calling method to deal with. I have seen API clients on GitHub and Codeplex which use each of these options. Is there a recommended approach for client libraries or are all of them valid?