我试图在出现错误的情况下通过AlaMofires的回调访问
我有一个枚举,它处理
enum BackendAPIErrorManager: Error {
case network(error: Error)
case apiProvidedError(reason: String) // this causes me problems
...
}
在我的请求中,如果有错误,我将适用的错误存储到Alamofire提供的
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 { 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
}
}
如果出现返回
如何从返回的错误中获取
要能够在符合
extension BackendAPIErrorManager: LocalizedError {
var errorDescription: String? {
switch self {
case .apiProvidedError:
return reason
}
}
}
原因有点模糊(因为关于
您可以在这里找到更多细节:如何在Swift中提供带有错误类型的本地化描述?