Skip to content

Instantly share code, notes, and snippets.

@bill350
Created April 1, 2018 22:03
Show Gist options
  • Select an option

  • Save bill350/830f0ecbfd9e847db5ef2d473c6a95c7 to your computer and use it in GitHub Desktop.

Select an option

Save bill350/830f0ecbfd9e847db5ef2d473c6a95c7 to your computer and use it in GitHub Desktop.
extension Error {
var localizedMessage: String {
if let error = self as? SignIn.Error { return error.underlying?.localizedMessage ?? error.localizedMessage }
if let error = self as? Network.Error { return error.localizedMessage }
if let error = self as? Store.Error { return error.localizedMessage }
return L10n.commonErrorMessage // Fallback error message
}
var underlying: Swift.Error? {
if let error = self as? SignIn.Error { return error.underlying }
if let error = self as? Network.Error { return error.underlying }
return nil
}
}
@eduardbosch
Copy link

I think this could be improved by casting errors to Underlying or Localizable like this:

extension Error {

    var localizedMessage: String {
        if let error = self as? Underlying,
           let message = error.underlying?.localizedMessage {
            return message
        }

        if let error = self as? Localizable {
            return error.localizedMessage
        }

        return L10n.commonErrorMessage // Fallback error message
    }

    var underlying: Swift.Error? {
        if let error = self as? Underlying {
            return error.underlying
        }

        return nil
    }
}

This way you can just add new errors and they will work out of the box.

What do you think?

If you want to override a particular error case, you can just add it.

@bill350
Copy link
Author

bill350 commented Jun 18, 2018

Hi Eduard, thank you for your feedback!

Yes, I agree with you, we can improve the code below.

For the Medium post & to be sure by reading the code that we manage all potential subcases, we've put all cases separately.

The opposite is good too, as you expose, by generalize the behavior and specify it after.
That makes sense ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment