Zorgan
Zorgan

Reputation: 9123

How to return an error from a HTTPS Cloud Function?

Calling a Cloud Function from an iOS app looks like this:

var functions = Functions.functions()
functions.httpsCallable(name).call(data){ (result, error) in
    // Code here
}

How can I send an error from my Cloud Function, so it will get picked up in the above code? For example:

Cloud Function:

exports.joinGame = functions.https.onCall((data, context) => {
     return Error("The game is full")
})

SwiftUI:

var functions = Functions.functions()
functions.httpsCallable("joinGame").call(data){ (result, error) in
    print(error) // "The game is full"
}

Upvotes: 2

Views: 521

Answers (1)

Asperi
Asperi

Reputation: 257749

I'm still not sure where do you want to return error... but here is some variants of possible handling:

@State private var error: Error?

var body: some View {
   VStack {
     Text("Wait for Error")
       .onAppear {
         functions.httpsCallable("joinGame").call(data){ (result, error) in
            print(error) // "The game is full"
            DispatchQueue.main.async {
               self.error = error
            }
         }
     }
     if nil != error {
        Text("Got error!")   // << do anything with error here
     }
   }
   .onChange(of: error) { newError in
                            // << or here 
   }
}

Upvotes: 2

Related Questions