Juan Herrero Diaz
Juan Herrero Diaz

Reputation: 843

How to nest low level errors and higher level errors?

I have a custom error type, for low level HTTP problems:

enum APIClientError: ErrorType {
    case NetworkError
    ...
}

In a higher level layer I have another error type:

enum SignInError: ErrorType {
    case InvalidUser
    ...
}

The problem I have is that those APIClientError instances need to bubble up to the higher level layer and in my function I need to return maybe an APIClientError, maybe an SignInError.

How can I declare a function like that? I tried

typealias LoginResult = Result<SuccessType, ErrorType>

But I does not work ('Using ErrorType' as a concrete type conforming to protocol 'ErrorType' is not supported').

How can I nest error types from different layers in Swift?

Upvotes: 0

Views: 72

Answers (1)

gregkerzhner
gregkerzhner

Reputation: 766

I am also scratching my head about this. The only way I can think of doing it is like this:

 enum APIClientError: ErrorType {
   case NetworkError
   ...
 }


 enum SignInError: ErrorType {
   case InvalidUser
   //note, the name of the case can't be the same as the type of the error due to compiler errors
   case APIError(APIClientError)
 }

This way errors will bubble up. The only annoying thing about this would be unwrapping multiple levels of error nesting by the code that handles the errors.

Upvotes: 1

Related Questions