I'm starting to run into this sort of dilemma while many third-party APIs, but I will use MongoDB for my examples. Consider the following code:
var settings = MongoClientSettings.FromConnectionString(connectionString);
settings.ServerApi = new ServerApi(ServerApiVersion.V1);
_mongoClient = new MongoClient(settings);
_northAmericaServer = _mongoClient.GetDatabase("server_na");
_userCollection = _mongoDatabaseServers.GetCollection<Entry>("users");
_allUsers = _userCollection.Find("{}");
There are, at least, 4 (meaningful) exceptions that may come out of that. Having an invalid connection string format, having bad credentials, Entry
not being a proper representation of the database's documents, Find()
using a malformed filter string, etc.
Since C# doesn't implement a throws
clause, it isn't straightforwardly obvious to me exactly what can go wrong while using third-party APIs, such as this. The exceptions that I mentioned earlier came from my experience experimenting with MongoDB today.
Documentation (if any) doesn't necessarily point out that kind of thing, and even if it did you might not trust it unless it was somehow autogenerated to list every possible exception from a method call.
So ultimately, I have to peek at the source code of the library (in this case MongoDB's driver) to have a better idea of what kind of exceptions a particular method might throw.
There's been a question about finding out whether a method throws here: https://stackoverflow.com/questions/18316535/how-to-know-if-some-method-can-throw-an-exception/18316567#18316567 (you can't, practically) - but that's not really the core of my problem: I want to know how to properly approach a third-party API in a situation where I am unfamiliar with the things that can go wrong with it.
I understand that exceptions aren't meant to be used for flow control, and that they often signal the application reaching an impossible state - and some exceptions are fatal and there's no point in trying to recover from them - but it seems reasonable for my application to try to address some of the exception(s) e.g. maybe my application can retrieve an up-to-date connection string from my authoritative server.
Again, it's not really about MongoDB in particular - it's just that I seem to have developed some degree of paranoia when calling any third-party API as I just don't know what can go wrong, and also a degree of disappointment when I think that I probably could've handled it reasonably if only I knew.
I could of course wrap the entire snippet in a try catch
but that wouldn't afford me the precision I'm looking for.
What should a developer do when calling third-party APIs that could potentially throw, yet is unable to discern exactly how or when?