Home > OS >  Handling function errors
Handling function errors

Time:11-24

I don't understand from the documentation how to do the error handling, I have the following:

func myFunc() async -> TransactionsClassAModel {
    let url = URL(string: "..."))
    
    let undecodedData = try! await networkingTools.afRequest(url: url!)
    let decodedData = try! JSONDecoder().decode(TransactionsClassAModel.self, from: undecodedData)
    
    return decodedData
}

I tried something like:

do {
    let undecodedData = try await networkingTools.afRequest(url: url!)
    try JSONDecoder().decode(TransactionsClassAModel.self, from: undecodedData)
} catch {
    print("error: ", error)
}

and the return statement says Cannot find 'decodedData' in scope and a warning: Result of call to 'decode(_:from:)' is unused

Can someone explain me how this works please.

Thanks

CodePudding user response:

The simplest fix is creating one do block, from which you return if everything is fine. And one catch block which will happen if anything is going wrong. You also have to adjust your function signature to return optional value, since in the case of failure you probably won't have a TransactionsClassAModel:

func myFunc() async -> TransactionsClassAModel? {

    let url = URL(string: "...")

    do {

        let undecodedData = try await networkingTools.afRequest(url: url!)
        let decodedData = try JSONDecoder().decode(TransactionsClassAModel.self, from: undecodedData)
        /* do anything you need */
        return decodedData // success
    } catch {
        print(error)
        return nil // no object in this case
    }
}

you can also separate blocks, so each try is in its own block, e.g.:

func myFunc() async -> TransactionsClassAModel? {

    let url = URL(string: "...")

    var undecodedData: Data // or optional Data? if function can return nil
    do {
        let undecodedData = try await networkingTools.afRequest(url: url!)
    } catch {
        print("Failed in afReqest: \(error)")
        return nil
    }

    var decodedData: TransactionClassModel?
    do {
        decodedData = try JSONDecoder().decode(TransactionsClassAModel.self, from: undecodedData)
    } catch {
        print("Failed in decode: \(error)")
        return nil
    }
    return decodedData
}

You can also separate data decoding into private function, and return on that function call:

private func decodeMyData(_ undecodedData; Data) -> TransactionsClassAModel? {
    do {
        return try JSONDecoder().decode(TransactionsClassAModel.self, from: undecodedData)
    } catch {
        print("Failed in decode: \(error)")
        return nil
    }
}

func myFunc() async -> TransactionsClassAModel? {

    let url = URL(string: "...")

    do {
        let undecodedData = try await networkingTools.afRequest(url: url!)
        return decodeMyData(undecodedData)
    } catch {
        print("Failed in afReqest: \(error)")
        return nil
    }
}
  • Related