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?

1
  • Do you see a different behavior? Commented Jun 4, 2018 at 21:24

1 Answer 1

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) {
      ...
    }
  });
} 
Sign up to request clarification or add additional context in comments.

5 Comments

can you also give an example of how to catch this error in the future instance of the above async function?thanks
Sorry, I don't understand your question. You just need to await the call and wrap it with try/catch.
Apologize for the confusion. What I mean is if you have assigned this to a variable: Future<void> asyncFunction = asyncFunction1(); When we add asyncFunction.catchError((error){}), can this catch the exception that already caught in the above block?
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.
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<void> asyncFunction async{ try{...}catch{} } Future<void> asyncInstance = asyncFunction; asyncInstance.catchError((error){}); Hmm, the code is a bit hard to read, maybe i should create a question for it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.