How to hold override throw from task

I try to pass catch the exrror , expecting "InvalidResponse" to be printed with print("expect invalid response printed") inside the top most catch { }

anyway to pass the catch error to outside of the task ?? (without holding value with self.myerror ) ??

class Bar2 {
    var atask: Task<(), Error>?
    var myerror: NetworkError?
    
    func bottomfunc() async throws {
        throw NetworkError.timeout
    }
    
    func topfunc() async throws {
            do {
                try await bottomfunc()
            } catch {
                print("topfunc catch called")
                throw NetworkError.unauthorised
            }
    }
    
    func coverfunc() {
       let mytask = Task {
            do {
                try await topfunc()
            }
            catch {
                print("coverfunc catch called")
                myerror = NetworkError.invalidResponse
                throw NetworkError.invalidResponse
            }
        }
        mytask.cancel()
        atask = mytask
    }
}

let a = Bar2()
a.coverfunc()
 do {
     try a.atask
 } catch {
     print("expect invalid response printed")
     print(error)
 }
print(a.myerror)

Shouldn't this be try a.atask.value instead? If you request the task's returned value it should wait until the task is complete and throw if the task ended with an error, whereas if you request the task itself you'll get the task whether it is completed or not and whether it finished with an error or not.

2 Likes