I am building a simple REST client in Swift 2. The methods the client offers can return errors. Every method returns the same errors (network problem, unauthorized, etc...). But each method can also return "specialized" error, than are needed only for the method itself.

I am trying to "extend" my ErrorType enum to match those "specialized" errors. This is my code:

// Specialized error type
public protocol CommandError: ErrorType {}

// A command that does not have specialized errors
public enum NoCommandError: CommandError {}

// The "Authorize" method returns errors
public enum AuthorizeError: CommandError {
    case WrongAuthorizeCode
    case WrongRequestId

// The errors the client can return
public enum ClientError<T: CommandError>: ErrorType {
    case Deserialization
    case Networking(internalError: NSError)
    case CommandError(commandError: T)
    case Unknown

// For any method that does not return specialized errors
public typealias ClientErrorDefault = ClientError<NoCommandError>

And I can easily pattern-match on the errors depending on which method I call. Here is an example:

func testAuthorize() -> ClientError<AuthorizeError> {
    return ClientError.CommandError(commandError: AuthorizeError.WrongAuthorizeCode)

func testOther() -> ClientErrorDefault {
    return ClientError.Deserialization

func matchError() {
    let error = testAuthorize()
//    let error = testOther()

    switch error {
    case .Deserialization: print("Deserialization")
    case .Networking(let e): print("Networking: \(e)")
    case .Unknown: print("Unknown")
    case .CommandError(let e): print(e)


(My playground code)

What do you think about this solution ?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.