3 ms·
Depends a bit what you mean by API. For APIs I usually don't log anything, it is the responsibility of the user to provide logging. Otherwise you end up with co
by raxxorraxor 4y ago
Depends a bit what you mean by API. For APIs I usually don't log anything, it is the responsibility of the user to provide logging. Otherwise you end up with countless logs from sub modules and probably many different logging frameworks. But not logging anything does mean that the API needs to supply important information in its responses to user calls. There are exceptions though and it depends on the type of API. The typical web API is already one in most cases.
Whether you just throw an exception or handle it yourself and package any error into a neat error object has advantages and disadvantages. Disadvantage to just throwing an exception is that the user might not get a sensible context. The call stack might not mean much to the user if he doesn't know about internal workings. But the advantage is that there is a uniform way of handling exception. The user immediately knows that something went wrong if an exception is thrown somewhere on a lower level. If the API handles the exception itself, it might be able to add the relevant information as to what caused the error, especially for common errors. In that case the user needs to know how to parse the error responses of your API though.
You should never just let the program run after it encountered an exception without informing the user. A log cannot sensibly inform an application about errors at runtime and this "swallowing" of exceptions is much more difficult for the user to handle or even to know if something went wrong.
I think the only rule of thumb is really that it is primarily the responsibility of the user to handle error and log application messages. But when I think of API I think of interfaces to specific devices or software, there are completely different rules for web APIs. Those cannot just throw exception to the user anyway. They also often have many users within one execution environment, so internal logging can certainly make sense.
Another topic is that error != exception and different rules might apply.