[英]Alamofire+Combine: how to get custom error type out of AFError
I'm using Alamofire and its Combine helpers to do a simple network request as follows:我正在使用 Alamofire 和它的 Combine 助手来做一个简单的网络请求,如下所示:
class AlamofireClient {
func getData<T: Decodable>(request: URLRequestConvertible) -> AnyPublisher<T, APIError> {
AF.request(request)
.validate()
.publishDecodable(type: T.self)
.value()
.mapError(APIError.init(error:))
.eraseToAnyPublisher()
}
}
enum APIError: Error {
init(error: AFError) {
self = .network
}
case network
case custom(Int, String, String)
var message: String {
switch self {
case .network:
return "Network Error"
case .custom(let code, let message, let technicalMessage):
return "Custom error info are: \(code) -- \(message) -- \(technicalMessage)"
}
}
}
I'm stuck at extracting the custom error info that is returned from the server, which's in my case has 3 items: code, message and technicalMessage.我一直在提取从服务器返回的自定义错误信息,在我的情况下有 3 个项目:代码、消息和技术消息。
So i had worked over similar situation where i wants to pass my own Error, instead of Alamofire.所以我在类似的情况下工作过,我想通过我自己的错误,而不是 Alamofire。 Please see the below code implementation i used, its working for me.
请参阅我使用的以下代码实现,它对我有用。 Hopefully it will help some one too.
希望它也能帮助一些人。
public func request<T>(response: @escaping (AnyPublisher<T, MyNetworkError>) -> ()) where T : Decodable {
response(
MyNetwork.shared.sendRequest(path: “sample/url/endpoints”)
.validate()
.publishDecodable(type: T.self)
.value()
.mapError{MyNetworkError.networkError(error: ($0 as Error))}
.eraseToAnyPublisher())
}
While my own error looks like below.虽然我自己的错误如下所示。
public enum MyNetworkError: Error {
case networkError(error: Error)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.