【问题标题】:Alamofire Error.localizedDescription - The operation couldn’t be completedAlamofire Error.localizedDescription - 操作无法完成
【发布时间】:2017-03-01 05:31:42
【问题描述】:

如果出现错误,我正在尝试通过 Alamofire 的回调访问 .localizedDescription 属性

我有一个枚举,它处理与Alamofire docs 非常相似的Error 类型

enum BackendAPIErrorManager: Error {
case network(error: Error)
case apiProvidedError(reason: String) // this causes me problems
...
}

在我的请求中,如果出现错误,我会将适用的错误存储到 Alamofire 提供的 .failure 案例中,如下所示:

private func resultsFromResponse(response: DataResponse<Any>) -> Result<Object> {
    guard response.result.error == nil else {
        print(response.result.error!)
        return .failure(BackendAPIErrorManager.network(error: response.result.error!))
    }

    if let jsonDictionary = response.result.value as? [String: Any], let errorMessage = jsonDictionary["error"] as? String, let errorDescription = jsonDictionary["error_description"] as? String  {
        print("\(errorMessage): \(errorDescription)")
        return .failure(BackendAPIErrorManager.apiProvidedError(reason: errorDescription))
    }
    ....
}

调用该方法的位置:

func performRequest(completionHandler: @escaping (Result<someObject>) -> Void) {
    Alamofire.request("my.endpoint").responseJSON {
        response in

        let result = resultsFromResponse(response: response)
        completionHandler(result)
    }
}

然后当我调用performRequest(:) 方法时,我会在完成处理程序中检查错误:

performRequest { result in 
    guard result.error == nil else {
        print("Error \(result.error!)") // This works 
        //prints apiProvidedError("Error message populated here that I want to log")

        print(result.error!.localizedDescription) // This gives me the below error 
    }
}

如果出现返回.failure(BackendAPIErrorManager.apiProvidedError(reason: errorDescription)) 的错误,我会收到以下错误

The operation couldn’t be completed. (my_proj.BackendErrorManager error 1.)

如何从返回的错误中获取String 值?我试过.localizedDescription 没有运气。任何帮助都会很棒!

【问题讨论】:

    标签: ios swift alamofire


    【解决方案1】:

    为了能够在符合Error 协议的自定义BackendAPIErrorManager 上调用.localizedDescription,您需要添加以下代码:

    extension BackendAPIErrorManager: LocalizedError {
      var errorDescription: String? {
        switch self {
          case .apiProvidedError:
            return reason
        }
      }
    }
    

    原因有点模糊(因为关于Error 协议如何工作的文档还不太详细)但基本上,在 Swift 3 中,为了能够提供本地化的错误描述(和其他相关信息),你需要符合新的LocalizedError 协议。

    您可以在此处找到更多详细信息: How to provide a localized description with an Error type in Swift?

    【讨论】:

      猜你喜欢
      • 2019-05-27
      • 2013-10-31
      • 2013-07-25
      • 2012-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-04
      相关资源
      最近更新 更多