0

I'm trying to check what exact error a request might throw by doing some custom checks and throw my own custom errors.

if let cause = resource.latestError?.cause {
    if case RequestError.Cause.RequestCancelled = cause {

    }
}

I get this error:

Argument type 'RequestError.Cause.RequestCancelled.Type' does not conform to expected type '_ErrorCodeProtocol'

Any ideas how I could check what the exact cause of the error is and then return my own custom errors?

apunn
  • 97
  • 8

1 Answers1

3

Siesta’s error causes are open to extension and thus not an enum, so the if case syntax doesn’t work with them. (The compiler error you’re getting is because Swift thinks you’re trying to use case to extract an error code from an error that doesn’t have one.)

Siesta’s error causes are instead a tree of distinct types. Instead of using if case, match error causes using is:

if let cause = resource.latestError?.cause {
  if cause is RequestError.Cause.RequestCancelled {

  }
}

…or simply:

if resource.latestError?.cause is RequestError.Cause.RequestCancelled {

}

…or if you need to assign the type-narrowed error to a variable so you can do something further with it:

if let cause = resource.latestError?.cause as? RequestError.Cause.RequestCancelled {

}
Paul Cantrell
  • 9,175
  • 2
  • 40
  • 48
  • Thanks! That helps a lot. How would I be able to differentiate between a "RequestCancelled" and a "Network Error"? Considering networkError is a member of RequestCancelled, how can I check for one or the other as they both represent two different types of errors. – apunn Dec 28 '17 at 21:19
  • I think you’re confused; the code above does what you’re asking for. RequestCancelled _has a_ network error, not _is a_ network error. The code above will only match cancellations. The [error types defined by Siesta](https://bustoutsolutions.github.io/siesta/api/Structs/RequestError/Cause.html) are only for errors Siesta itself detects; if the underlying networking layer reports an error, then Siesta just passes that error straight through in the `cause`. – Paul Cantrell Dec 28 '17 at 21:30
  • 1
    That makes sense. Thank you for a well written explanation. – apunn Dec 29 '17 at 02:03