如果第一次解码失败,请使用Combine和Swift对另一个响应进行解码



我有以下模型:

struct Response: Decodable {
let message: String
}
struct ErrorResponse: Decodable {
let errorMessage: String
}
enum APIError: Error {
case network(code: Int, description: String)
case decoding(description: String)
case api(description: String)
}

我正在尝试获取一个url,并使用以下流解析JSON响应:

func fetch(url: URL) -> AnyPublisher<Response, APIError> {
URLSession.shared.dataTaskPublisher(for: URLRequest(url: url))
// #1 URLRequest fails, throw APIError.network
.mapError { .network(code: $0.code.rawValue, description: $0.localizedDescription) }
// #2 try to decode data as a `Response`
.tryMap { JSONDecoder().decode(Response.self, from: $0.data) }
// #3 if decoding fails, decode as an `ErrorResponse`
//    and throw `APIError.api(description: errorResponse.errorMessage)`
// #4 if both fail, throw APIError.decoding

// #5 return
.eraseToAnyPublisher()
}

我对#3有一个问题:如何解码tryMap部分之后的原始数据?

似乎我能访问的唯一值是来自tryMap的错误,但我需要原始数据来解码ErrorRepsonse

注意:不幸的是,错误响应带有200状态,区分它们的唯一方法是解码它们。

您可以使用flatMap并在其中处理解码:

URLSession.shared.dataTaskPublisher(for: URLRequest(url: url))
// #1 URLRequest fails, throw APIError.network
.mapError { 
APIError.network(code: $0.code.rawValue, description: $0.localizedDescription) 
}
.flatMap { data -> AnyPublisher<Response, APIError> in
// #2 try to decode data as a `Response`
if let response = try? JSONDecoder().decode(Response.self, from: data) {
return Just(response).setFailureType(to: APIError.self)
.eraseToAnyPublisher()
}
do {
// #3 if decoding fails, decode as an `ErrorResponse`
let error = try decoder.decode(ErrorResponse.self, from: data)

// and throw `APIError.api(description: errorResponse.errorMessage)`
return Fail(error: APIError.api(description: errorResponse.errorMessage))
.eraseToAnyPublisher()
} catch {
// #4 if both fail, throw APIError.decoding
return Fail(error: APIError.decoding(description: error.localizedDescription))
.eraseToAnyPublisher()
}
}

编辑

如果你想在";纯";综合起来,那么您仍然希望使用flatMap来访问原始数据并避开原始可能的网络错误,然后使用tryCatch来处理故障路径。

注意,步骤#4介于步骤#3的两个部分之间:

URLSession.shared.dataTaskPublisher(for: URLRequest(url: url))
// #1 URLRequest fails, throw APIError.network
.mapError { 
APIError.network(code: $0.code.rawValue, description: $0.localizedDescription) 
}
.flatMap { v in
Just(v)
// #2 try to decode data as a `Response`
.decode(type: Response.self, decoder: JSONDecoder())
// #3 if decoding fails,
.tryCatch { _ in
Just(v)
// #3.1 ... decode as an `ErrorResponse`
.decode(type: ErrorResponse.self, decoder: JSONDecoder())

// #4 if both fail, throw APIError.decoding
.mapError { _ in APIError.decoding(description: "error decoding") }
// #3.2 ... and throw `APIError.api
.tryMap { throw APIError.api(description: $0.errorMessage) }
}
// force unwrap is not terrible here, since you know 
// that `tryCatch` only ever throws APIError
.mapError { $0 as! APIError }
}

最新更新