gpt4 book ai didi

dart - future 抛出异常句柄不在原点将来

转载 作者:行者123 更新时间:2023-12-03 02:58:17 26 4
gpt4 key购买 nike

我试图理解, Dart future 异常如何工作。我读了一篇很好的文章link。但是,当我嵌套了Future且它们中的第一个抛出错误时,如何在第二个Future上处理此错误。

为了澄清,我的意思是看下面的示例。

import 'dart:async';

void main() {

var fur1 = new Future<int>(() => 45);
fur1.then((value) {
throw new StateError('Hello error');
});

var fur2 = new Future<int>(() => 24);
fur2.then((value) {
fur1.then((value1) {
print(value1);
});
print(value);
}).catchError((err) => print(err));
}

在fur1中,我引发了一个异常,并期望在fur2中捕获错误,但是编译器显示消息

Unhandled exception: Bad state: Hello error



将来有可能处理嵌套错误吗?我知道,我可以在这里使用completer类,也许这是解决方案?

最佳答案

我不确定您实际上要完成什么。

但对我来说,这种方式

import 'dart:async';

void main() {

var fur1 = new Future<int>(() => 45);
// fur1.then((value) {
// throw new StateError('Hello error');
// });

var fur2 = new Future<int>(() => 24);
fur2.then((value) {
var x = fur1.then((value1) {
print(value1);
throw new StateError('Hello error'); // <= inner exception
});
print(value);
return x; // <= return future
}).catchError((err) => print('catchError: ${err}'));
}

或者这样

import 'dart:async';

void main() {

var fur1 = new Future<int>(() => 45);
fur1.then((value) {
throw new StateError('Hello1 error');
}).catchError((err) => print('catchError1: ${err}'));

var fur2 = new Future<int>(() => 24);
fur2.then((value) {
var x = fur1.then((value1) {
print(value1);
throw new StateError('Hello2 error'); // <= inner exception
});
print(value);
return x; // <= return future
}).catchError((err) => print('catchError2: ${err}'));
}

catchError1: Bad state: Hello1 error
24
45
catchError2: Bad state: Hello2 error

关于dart - future 抛出异常句柄不在原点将来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24257905/

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