【发布时间】:2016-12-12 23:07:35
【问题描述】:
我有一个网络管理器类,它与我们的服务后端进行所有通信。当网络请求可能失败时,我正在努力为用户提供良好的体验。
现在,网络管理器类发出请求以向后端进行身份验证:
internal func authenticate(withEmailAddress emailAddress: String, andPassword password: String, withCompletion completion: @escaping (Result<Data>) -> Void) {
// ...Create the request...
task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in
if let requestError = error as? NSError {
// ...Handle CFNetworkErrors (-1001, etc.)...
}
if let httpResponse = response as? HTTPURLResponse {
// ...Handle the response codes (200, 400, 401, 500)...
} else {
// ...Handle the response not being of type `HTTPURLResponse`...
}
})
// ...Start the task...
}
我有另一个类管理 Data 或 Error 到完成处理程序的返回,它基于响应的状态代码或请求的错误。
查看list of HTTP status codes 和CFNetworkErrors 列表后,我可以看到处理此类错误的可能性很多。我意识到并非所有CFNetworkErrors 都适合我的情况,但我仍然需要处理一长串错误。
除了打开requestError.code之外,我还有什么方法可以处理可能出现的错误吗?
如果我要处理所有CFNetworkErrors,那么我最终会得到一个非常长的逻辑块来检查这样的代码:
switch code {
case -1005: // ...Handle error...
case -1001: // ...Handle error...
case 1: // ...Handle error...
case 200: // ...Handle error...
// ...Handle the rest of the errors...
default: // ...Handle error...
}
我也会得到一个很长的块来处理所有适当的响应状态代码,如下所示:
switch response.statusCode {
case 200: // ...Do something with data...
case 400: // ...Handle missing user credentials...
case 401: // ...Handle incorrect credentials...
case 500: // ...Handle internal server error...
// ...Handle the rest of the status codes...
default: // ...Handle default error...
}
在尝试处理可能遇到的所有网络错误时,您能否给我一些指导?
【问题讨论】:
标签: ios http-status-codes urlsession