当响应数据不包含要使用 Combine 解码的对象时,我如何抛出错误?
How could I throw an Error when response data does not contain an object to decode with Combine?
我有一个发布者包装器结构,我可以在其中处理响应状态代码。如果状态代码不在 200..300 范围内,它会 return 对象,否则会抛出错误。效果很好。
public func anyPublisher<T:Decodable>(type: T.Type) -> AnyPublisher<T, Error> {
return URLSession.shared.dataTaskPublisher(for: urlRequest)
.tryMap { output in
guard let httpResponse = output.response as? HTTPURLResponse, 200..<300 ~= httpResponse.statusCode else {
throw APIError.unknown
}
return output.data
}
.decode(type: T.self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
使用:
let sendNewUserPublisher = NetworkPublisher(urlRequest: request).anyPublisher(type: User.self)
cancellationToken = sendNewUserPublisher.sink(receiveCompletion: { completion in
if case let .failure(error) = completion {
NSLog("error: \(error.localizedDescription)")
}
}, receiveValue: { post in
self.post = post
})
如上,即使响应数据不包含要解码的对象,我也想处理错误。
public func anyPublisher() -> AnyPublisher<URLSession.DataTaskPublisher.Output, URLSession.DataTaskPublisher.Failure> {
return URLSession.shared.dataTaskPublisher(for: urlRequest)
// I'd like to handle status code here, and throw an error, if needed
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
提前感谢您提供的任何帮助。
我建议创建一个 Publisher
来处理 HTTP 响应状态代码验证,并将其用于您的其他两个发布者 - 处理空请求正文的发布者和解码正文的发布者。
如果在验证其状态代码后仍需要 HTTPURLResponse
对象:
extension URLSession.DataTaskPublisher {
/// Publisher that throws an error in case the data task finished with an invalid status code, otherwise it simply returns the body and response of the HTTP request
func httpResponseValidator() -> AnyPublisher<Output, CustomError> {
tryMap { data, response in
guard let httpResponse = response as? HTTPURLResponse else { throw CustomError.nonHTTPResponse }
let statusCode = httpResponse.statusCode
guard (200..<300).contains(statusCode) else { throw CustomError.incorrectStatusCode(statusCode) }
return (data, httpResponse)
}
.mapError { CustomError.network([=10=]) }
.eraseToAnyPublisher()
}
}
或者,如果您不关心响应的任何其他属性,只关心其状态代码是否有效:
func httpResponseValidator() -> AnyPublisher<Data, CustomError> {
tryMap { data, response in
guard let httpResponse = response as? HTTPURLResponse else { throw CustomError.nonHTTPResponse }
let statusCode = httpResponse.statusCode
guard (200..<300).contains(statusCode) else { throw CustomError.incorrectStatusCode(statusCode) }
return data
}
.mapError { CustomError.network([=11=]) }
.eraseToAnyPublisher()
}
然后您可以使用它来重写您的 anyPublisher
函数的两个版本:
extension URLSession.DataTaskPublisher {
func anyPublisher<T:Decodable>(type: T.Type) -> AnyPublisher<T, Error> {
httpResponseValidator()
.decode(type: T.self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
func anyPublisher() -> AnyPublisher<Output, CustomError> {
httpResponseValidator()
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
}
我有一个发布者包装器结构,我可以在其中处理响应状态代码。如果状态代码不在 200..300 范围内,它会 return 对象,否则会抛出错误。效果很好。
public func anyPublisher<T:Decodable>(type: T.Type) -> AnyPublisher<T, Error> {
return URLSession.shared.dataTaskPublisher(for: urlRequest)
.tryMap { output in
guard let httpResponse = output.response as? HTTPURLResponse, 200..<300 ~= httpResponse.statusCode else {
throw APIError.unknown
}
return output.data
}
.decode(type: T.self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
使用:
let sendNewUserPublisher = NetworkPublisher(urlRequest: request).anyPublisher(type: User.self)
cancellationToken = sendNewUserPublisher.sink(receiveCompletion: { completion in
if case let .failure(error) = completion {
NSLog("error: \(error.localizedDescription)")
}
}, receiveValue: { post in
self.post = post
})
如上,即使响应数据不包含要解码的对象,我也想处理错误。
public func anyPublisher() -> AnyPublisher<URLSession.DataTaskPublisher.Output, URLSession.DataTaskPublisher.Failure> {
return URLSession.shared.dataTaskPublisher(for: urlRequest)
// I'd like to handle status code here, and throw an error, if needed
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
提前感谢您提供的任何帮助。
我建议创建一个 Publisher
来处理 HTTP 响应状态代码验证,并将其用于您的其他两个发布者 - 处理空请求正文的发布者和解码正文的发布者。
如果在验证其状态代码后仍需要 HTTPURLResponse
对象:
extension URLSession.DataTaskPublisher {
/// Publisher that throws an error in case the data task finished with an invalid status code, otherwise it simply returns the body and response of the HTTP request
func httpResponseValidator() -> AnyPublisher<Output, CustomError> {
tryMap { data, response in
guard let httpResponse = response as? HTTPURLResponse else { throw CustomError.nonHTTPResponse }
let statusCode = httpResponse.statusCode
guard (200..<300).contains(statusCode) else { throw CustomError.incorrectStatusCode(statusCode) }
return (data, httpResponse)
}
.mapError { CustomError.network([=10=]) }
.eraseToAnyPublisher()
}
}
或者,如果您不关心响应的任何其他属性,只关心其状态代码是否有效:
func httpResponseValidator() -> AnyPublisher<Data, CustomError> {
tryMap { data, response in
guard let httpResponse = response as? HTTPURLResponse else { throw CustomError.nonHTTPResponse }
let statusCode = httpResponse.statusCode
guard (200..<300).contains(statusCode) else { throw CustomError.incorrectStatusCode(statusCode) }
return data
}
.mapError { CustomError.network([=11=]) }
.eraseToAnyPublisher()
}
然后您可以使用它来重写您的 anyPublisher
函数的两个版本:
extension URLSession.DataTaskPublisher {
func anyPublisher<T:Decodable>(type: T.Type) -> AnyPublisher<T, Error> {
httpResponseValidator()
.decode(type: T.self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
func anyPublisher() -> AnyPublisher<Output, CustomError> {
httpResponseValidator()
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
}