Our team created a library that contains methods to call an external REST API. This library is then added as a Nuget package to other services (microservices) that will be hosted in Azure, so we want to be very conscious about performance and resource usage.
The code in the library was mostly autogenerated with NSwagStudio, and it makes requests to the external REST API, receives the response, checks the response's status code, and:
- If it is 200 returns the response
- If it something else (400, 404, 500) throws a custom exception with details of what happened.
We are discussing now about exception handling in this code, with 2 different points of view:
- We should avoid throwing exceptions as much as possible, therefore the library should be modified to return a code for each type of failed response. The rationale is that exceptions are costly and should be avoided as much as possible.
- We should keep using exceptions, even more in a shared library, to avoid the risk of clients not checking the return codes and failing to react to problems. Ex. a POST call to add an item returns a 400 and the client execution continues, unaware of the problem.
Reference (another section of the same document): Throw exceptions instead of returning an error code - Best Practices for exceptions - .NET | Microsoft Docs
Which option should we take?
There are several questions in Stackoverflow about throwing exceptions from libraries, but we couldn't find much about 2 conditions specific to us:
- These services will be running in Azure.
- This library is basically a wrapper to call a REST API.