gpt4 book ai didi

dart - 为什么 catchError 无法捕捉到错误?

转载 作者:行者123 更新时间:2023-12-02 18:49:44 27 4
gpt4 key购买 nike

最小可重现代码:

Future<void> foo() async => throw Future.error('Foo');

void main() {
foo().catchError(print);
}

我仍然在控制台上看到这个错误

Dart Unhandled Exception: Foo, stack trace:

如果我抛出 FlutterError(...),错误会被捕获但 Future.error(...) 会失败。原因是出现的错误本身就是一个Future,但是我该如何处理呢?

最佳答案

你的代码有两个问题:

异步标记的方法正在运行同步,直到第一次等待

你的 async标记的方法实际上并没有真正作为事件队列中的另一个事件运行,直到第一个 await正在发生。

在这种情况下,这意味着在我们有时间分配任何错误处理之前实际上抛出了异常,因此我们得到了一个错误。此行为可以在 catchError 的文档中找到:

Note that futures don't delay reporting of errors until listeners are added. If the first catchError (or then) call happens after this future has completed with an error then the error is reported as unhandled error.

https://api.dart.dev/stable/2.12.2/dart-async/Future/catchError.html

解决这个问题的方法是实际制作一个 await在抛出异常之前,让我们这样做:

Future<void> foo() async {
await Future<void>.value();
throw Future.error('Foo');
}

void main() {
foo().catchError(print);
}

但是我们现在收到以下错误作为我们需要研究的输出:

Instance of 'Future<dynamic>'
Unhandled exception:
Foo

Throw inside async block converts object to Future error

Instance of 'Future<dynamic>'是来自 print 的一行试图打印错误的方法。如我们所见,我们得到了一个 Future。对象在这里。这个对象其实就是从Future.error('Foo')创建的对象.

在 Dart 中我们可以 throw我们想要的任何对象。在 async标记的方法,这个对象将被打包在一个 Future.error 中.因此,在您的情况下,您实际所做的是 Future.error(Future.error('Foo')) .

然后您处理的是外部错误,而不是内部错误。如果我们这样做:

Future<void> foo() async {
await Future<void>.value();
throw Future.error('Foo');
}

Future<void> main() async {
await foo().catchError((Object obj) => (obj as Future).catchError(print));
}

这将返回:

Foo

因为我们现在调用 catchErrorFuture 上创建者 Future.error('Foo') .

关于dart - 为什么 catchError 无法捕捉到错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66952192/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com