【发布时间】: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 没有运气。任何帮助都会很棒!
【问题讨论】: