gpt4 book ai didi

swift - 使用 URLSession 和 Combine 处理 HTTP 状态代码

转载 作者:行者123 更新时间:2023-12-04 14:16:45 25 4
gpt4 key购买 nike

我正在尝试处理来自 DataTaskPublisher 的响应读取其响应状态代码。

当状态码大于 299 时,我想返回一个 ServiceError类型为失败。在我见过的每个例子中,我都使用了 .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()

最佳答案

enum ServiceErrors: Error { 
case internalError(_ statusCode: Int)
case serverError(_ statusCode: Int)
}

return URLSession.shared.dataTaskPublisher(for: urlRequest)
.tryMap { data, response in
guard let httpResponse = response as? HTTPURLResponse,
200..<300 ~= httpResponse.statusCode else {
switch (response as! HTTPURLResponse).statusCode {
case (400...499):
throw ServiceErrors.internalError((response as! HTTPURLResponse).statusCode)
default:
throw ServiceErrors.serverError((response as! HTTPURLResponse).statusCode)
}
}
return data
}
.mapError { $0 as! ServiceErrors }
.decode(type: T.self, decoder: JSONDecoder())
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
注意:我靠 this链接以制作我的错误处理程序。

关于swift - 使用 URLSession 和 Combine 处理 HTTP 状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59461539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com