I'm writing an API wrapper for an external API. How do I let the consumers know about specific errors that occur in wrapper?
If the consumer is supporting multiple languages, and the wrapper doesn't, I think it would be bad for me to send error-messages in just English text.
At first, to overcome this, I thought of using integer error codes. But, with this, I can only indicate type of error, and will not be able to send back some helpful data.
Now, I am thinking about using Exceptions or custom error objects. Either throw them directly or wrap them in a Result object like Result.failure(exception). But, I am not sure if I should do this. Here's what I will try to do:
class WrapperException(val error: WrapperError): Exception()
or
open class WrapperException: Exception()
class SessionCreationFailedException: WrapperException()
class InvalidRequestTokenException: WrapperException()
class RequestTokenExpiredException: WrapperException()
class SessionRevokedException(val failedSession: String): WrapperException()
class UnexpectedException: WrapperException()
Extending from WrapperException doesn't make sense because there might be exceptions due to code or other reasons like NullPointerException, SocketTimeoutException, etc.
At the end, the consumers will still have to do something like
when (exception) {
is ExceptionA -> handleExceptionA()
is ExceptionB -> handleExceptionB()
else -> somethingWentWrong()
}
I think I shouldn't try to categorize exceptions with WrapperException to evade else statement. And, for consumers to implement error-handling like this, they must know what exceptions a function can throw (some documentation might help here).
It, also, makes me feel that the wrapper functions will become unpredictable. In future updates, consumer might not expect ExceptionZ to appear, but technically, it can. So, maybe updating documentation and changelogs is most I can do here.
Should I avoid sending an error message? I am confused. Please help me understand how I can make it useful for consumers.