0
votes

here is my code api response for error:

 guard (error == nil) else {
     print("There was an error with your request: \(error)")
     return
 }

response error:

Optional(Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x7f90d551ce50 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=https://xxxxx.ie/service/delivery/login, NSErrorFailingURLKey=https://xxxxx.ie/service/delivery/login, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.})

how can get "The request timed out" and code to send user alert.

Note please share, what is best practice what is best practice for error and generate human readable message.

2
try after some time and check your internet connectivity . - Himanshu Moradiya
@HimanshuMoradiya yea the issue arise internet connectivity .. so i need to notify user the check internet connectivity - user7166107
NSError has code property and userInfo dictionary including the localized description. - vadian
ya just notify user try again or check internet connectivity in alert or something else - Himanshu Moradiya
@HimanshuMoradiya sound! but sometime error not for net connection - user7166107

2 Answers

1
votes

NSError has code and localizedDescription property. You can simply extract the information for example:

guard error == nil else {
    let code = error!.code
    let localizedDescription = error!.localizedDescription
    print(error!.userInfo) // here you can see what the userInfo dictionary contains
    let alertMessage = "An error with code \(code) occurred. Description: \(localizedDescription)"
    print(alertMessage)
    // or create an alert view controller to display the error message
    return
}
0
votes

You can check if the provided error is of type Error (was: NSError in Swift 2) and then access it's members, or the userInfo:

guard (error == nil) else {
    if let err = error as Error {
        let description = err.localizedDescription
        print("Error: \(description)"
    } else {
        // should not be reached at all, just to make sure we handle everything
        print("There was an error with your request: \(error)")
    }
     return
}

See: https://developer.apple.com/reference/foundation/nserror