Tom Andersen
Tom Andersen

Reputation: 7200

ErrorType in swift - how do I get an error code out?

I am passed an error - its an ErrorType - in a completion.

I can 'po' it in the debugger, but how do I get the number -1009 out in swift code. The only call I can find to make is 'debugDescription'. Is there a Dictionary in there?

Whoever made the ErrorType subclass is basically unknown to me.

po error
         ▿ Optional(Error Domain=NSURLErrorDomain Code=-1009 "The Internet   connection appears to be offline." UserInfo= {NSErrorFailingURLStringKey=https://xxxxxxxxxx.net/token, _kCFStreamErrorCodeKey=8, NSErrorFailingURLKey=https://xxxxxxxxxxx.net/token, NSLocalizedDescription=The Internet connection appears to be offline., _kCFStreamErrorDomainKey=12, NSUnderlyingError=0x145f7880 {Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={_kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8}}})

Upvotes: 8

Views: 4647

Answers (2)

yoAlex5
yoAlex5

Reputation: 34255

Xcode 8 and Swift 3 the conditional cast is always succeeds

let errorCode = (error as NSError).code

The alternative

let errorCode = error._code

Upvotes: 3

Said Sikira
Said Sikira

Reputation: 4533

Error code comes from Objective C NSError. To get the error code first try to cast ErrorType to an NSError. After you do that you can access the code via code property. You can achieve it like this:

if let error = error as? NSError {
    print(error.code) // this will print -1009
}

For more info, you can refer to the documentation

Upvotes: 5

Related Questions