如何从catchError中的Future.error获取值? [英] How to get the value from Future.error inside catchError?

查看:599
本文介绍了如何从catchError中的Future.error获取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void main() {
  foo().catchError((error) {
    if (error is Future) {
      error.then((value) => print('value = $value'));
    }
  });
}

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

错误被捕获在 catchError 内部,但是在该示例中,我无法检索 Future.error 的值,该值是 FooError

The error is caught inside catchError but I am not able to retrieve the value of Future.error which is FooError in this example.

推荐答案

您只是没有,这样做是没有意义的。

You just don't, there is no point in doing so.

您可以抛出错误:

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

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

或者如果出于某种原因而不方便,则可以使用 Future .error 创建一个已经存在错误的Future:

Or if that is for whatever reason not convinient, you can use Future.error to create a Future that will have an error already:

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

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

但实际上 c $ c> Future.error 是多余的,没有用。

But actually throwing a Future.error is redundant and not useful.

这篇关于如何从catchError中的Future.error获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆