0

I have this method.

asyncFunction1() async {
  Firestore.instance.runTransaction((transaction){
    var first = await transaction.something;
    var second = await secondInside();
  });
}

Now I want to call this method, and catch every error that happens inside. How would I propagate errors so that

try {asyncFunction1()} catch(e){}

catches all errors that happened inside runTransaction?

Tree
  • 29,135
  • 24
  • 78
  • 98

1 Answers1

3

Your inner function misses an async to be able to use await. If you add it, you can use try/catch

asyncFunction1() {
  Firestore.instance.runTransaction((transaction) async {
    try {
      var first = await transaction.something;
      var second = await secondInside();
    } catch(e) {
      ...
    }
  });
} 
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • can you also give an example of how to catch this error in the future instance of the above async function?thanks – Panda World Nov 13 '18 at 09:55
  • Sorry, I don't understand your question. You just need to await the call and wrap it with `try`/`catch`. – Günter Zöchbauer Nov 13 '18 at 10:05
  • Apologize for the confusion. What I mean is if you have assigned this to a variable: Future asyncFunction = asyncFunction1(); When we add asyncFunction.catchError((error){}), can this catch the exception that already caught in the above block? – Panda World Nov 13 '18 at 10:13
  • Why would you want to do this? I still don't think I understand the question but `catchError` is the canonical way of handling exceptions of async code, `try`/`catch` can only be used with `async`/`await`. – Günter Zöchbauer Nov 13 '18 at 10:21
  • The main reason for me is to trying to understand the relationship between future and async function.Maybe my example is bit confusing. Please let me give another one: Future asyncFunction async{ try{...}catch{} } Future asyncInstance = asyncFunction; asyncInstance.catchError((error){}); Hmm, the code is a bit hard to read, maybe i should create a question for it. – Panda World Nov 13 '18 at 10:28