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

paw*_*222 0 json swift decodable combine

我有以下模型:

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)
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用以下流程获取 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()
}
Run Code Online (Sandbox Code Playgroud)

我有一个问题#3:如何在tryMap零件之后解码原始数据?

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

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

New*_*Dev 5

您可以使用 aflatMap并处理其中的解码:

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()
      }
   }
Run Code Online (Sandbox Code Playgroud)

编辑

如果您想以“纯”组合方式执行此操作,那么您仍然希望使用 aflatMap来访问原始数据并避开原始可能的网络错误,然后使用它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 }
   }
Run Code Online (Sandbox Code Playgroud)

  • @pawello2222 - 更新为更纯粹的组合风格 (2认同)