Home > Net >  Decoding to another class in do-try-catch produces compile error
Decoding to another class in do-try-catch produces compile error

Time:11-15

I'm facing compile error. I trying to decode API response into custom class(struct actually). Our API returns several type of error (sometime it contain string but sometime it returns code (tuple [String: Int])) So I would like to decode into another class if first decoding failed.

If I try decoding into just one class, it is okay but if I try to decode into another class in catch scope, it produces compile error

Invalid conversion from throwing function of type '(Data?, URLResponse?, Error?) throws -> Void' to non-throwing function type '(Data?, URLResponse?, Error?) -> Void'

Do you know how to solve this?

  • I'm useing Swift5, Xcode 12.4
struct ErrorInfo: Codable {
    public let message: String?
    public let details: String?
    public let debugInformation: String?
}

struct ErrorInfoWithErrorCode: Codable {
    public let message: [String: Int] // this is the difference.
    public let details: String?
    public let debugInformation: String?
}

let request = URLRequest(url: URL(string: "https://www.google.com/")!)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let httpResponse = response as? HTTPURLResponse, !(200..<300).contains(httpResponse.statusCode) {
        do {
            let errorMessage = try decoder.decode(ErrorInfo.self, from: data)
            print(errorMessage)
        } catch  {
            let errorMessage = try decoder.decode(ErrorInfoWithErrorCode.self, from: data)
            print(errorMessage)
        } catch {
            fatalError()
        }
    }
}
task.resume()

Error message in playground.

error: MyPlayground.playground:28:54: error: invalid conversion from throwing function of type '(Data?, URLResponse?, Error?) throws -> Void' to non-throwing function type '(Data?, URLResponse?, Error?) -> Void'
let task = URLSession.shared.dataTask(with: request) { data, response, error in

CodePudding user response:

The other nested try needs a do also , You can try

do {
    let errorMessage = try decoder.decode(ErrorInfo.self, from: data)
    print(errorMessage)
} catch  {
    do {
        let errorMessage = try decoder.decode(ErrorInfoWithErrorCode.self, from: data)
        print(errorMessage)
    } catch {
        fatalError()
    }
}
  • Related