Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enums to design error types in Swift

Tags:

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.

Questions

Is there some other way I can use enums to accomplish this?

Is this even a "best practice"?

like image 235
sargturner Avatar asked Nov 18 '17 23:11

sargturner


1 Answers

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.

like image 158
Paulo Mattos Avatar answered Sep 22 '22 12:09

Paulo Mattos