如何解析来自网络请求的错误

how to parse the error from web request

这是我的代码 api 错误响应:

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

响应错误:

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.})

如何获取 "The request timed out" 和发送用户警报的代码。

注意请分享,什么是最佳实践什么是错误的最佳实践并生成人类可读的消息。

您可以检查提供的错误是否属于 Error 类型(在 Swift 2 中为 NSError),然后访问它的成员,或 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
}

参见:https://developer.apple.com/reference/foundation/nserror

NSErrorcodelocalizedDescription 属性。您可以简单地提取信息,例如:

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
}