我正在尝试处理通过DataTaskPublisher
读取其响应状态代码到达的响应。
当状态码大于299时,我想返回一个ServiceError
类型为Failure。在每一个例子,我已经看到我已经使用.mapError
并.catch
......在这种特殊情况下,从.flatMap
,我真的不知道如何处理发布响应返回错误,而不是TResponse
...
return URLSession.DataTaskPublisher(request: urlRequest, session: .shared)
.mapError{error in return ServiceError.request}
.flatMap{ data, response -> AnyPublisher<TResponse, ServiceError> in
if let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode){
return Just(data)
.decode(type: TResponse.self, decoder: JSONDecoder())
.mapError{error in return ServiceError.decode}
.eraseToAnyPublisher()
}else{
//???? HOW TO HANDLE THE ERROR?
}
}
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
如果我正确理解了您的目标,那么您需要
}else{
return Fail(error: ServiceError.badServiceReply)
.eraseToAnyPublisher()
}
简单的例子:
URLSession.shared
.dataTaskPublisher(for: URL(string: "https://www.google.com")!)
.receive(on: DispatchQueue.main)
.flatMap { _ in
Fail(error: URLError(URLError.unsupportedURL)).eraseToAnyPublisher()
} //for the sake of the demo
.replaceError(with: "An error occurred") //this sets Failure to Never
.assign(to: \.stringValue, on: self)
.store(in: &cancellableBag)
由于重新映射到发布者,将始终分配字符串“发生错误”Fail
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句