Maybe I'm just completely overthinking this but I am trying to use enums to handle errors from an API I am integrating with.
From the swagger documentation of this API I can see all of the possible responses that could be returned. I have written these out as a BaseError
enum:
enum BaseError: Error {
case badRequest // 400
case unauthorized // 401
case forbidden // 403
case unhandledError // XXX
...
}
Now in my client is where my problem starts.
My original hope was to take this BaseError
enum and extend / add additional cases onto it depending on which client I am in.
Something like:
enum ClientSpecificError: BaseError {
case clientError
}
Which would allow me to return an error like ClientSpecificError.unauthorized
Now I know this is not possible as enums cannot inherit other enums but I am missing some understanding on how I should accomplish this.
Is there some other way I can use enums to accomplish this?
Is this even a "best practice"?
What you can do instead is use associated values and store the lowel-level error in a dedicated case. For instance:
enum ClientSpecificError: Error {
case clientError
case baseError(BaseError)
}
Apple documentation:
However, it is sometimes useful to be able to store associated values of other types alongside these case values. This enables you to store additional custom information along with the case value, and permits this information to vary each time you use that case in your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With