1
void main() {
  foo().catchError((error) {
    print('Error caught = $error');
  });
}

Future<void> foo() {
  throw Future.error('FooError');
}

As I read the docs:

This is the asynchronous equivalent of a "catch" block.

If I use catch block, the error is caught. But my catchError isn't able to catch the error, but according to docs it should. Am I doing something wrong?


Note: I know I can use return instead of throw and the error will be then caught in catchError as stated by @CopsOnRoad here. My question is why catchError isn't catching a thrown error but catch block does catch that.

iDecode
  • 22,623
  • 19
  • 99
  • 186

1 Answers1

1

foo() throws an error before it returns the Future to the caller. So it's not that catchError isn't working, the error is just not passed back to the caller.

If you mark foo as async so that the function actually returns a Future, you'll see that the error is caught.

void main() {
  foo().catchError((error) {
    print('Error caught = $error');
  });
}

Future<void> foo() async {
  throw Future.error('FooError');
}

You'll see from the accepted answer of your linked post that their function is marked async so that a Future is actually returned that catchError can catch.

Having a function that returns Future<void> without being marked async and not returning a literal type of Future<void> really should be an error.

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52