Why catchError isn't able to catch the error?

一曲冷凌霜 提交于 2021-01-28 08:11:50

问题


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.


回答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.



来源:https://stackoverflow.com/questions/63560652/why-catcherror-isnt-able-to-catch-the-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!