Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

nserror

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}}})
like image 418
Tom Andersen Avatar asked Nov 19 '15 20:11

Tom Andersen


2 Answers

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

like image 139
Said Sikira Avatar answered Oct 06 '22 15:10

Said Sikira


Xcode 8 and Swift 3 the conditional cast is always succeeds

let errorCode = (error as NSError).code

The alternative

let errorCode = error._code
like image 43
yoAlex5 Avatar answered Oct 06 '22 17:10

yoAlex5