我們知道dart是一種單線程語言些侍,我們執(zhí)行異步操作借助的是它的 event loop 機(jī)制,F(xiàn)uture是我們最常用到的一個工具饭望,常見用法如下:
Future testFuture() {
... 此處進(jìn)行耗時操作
}
//調(diào)用處
main() async {
//第一種悔政,同步會阻塞
await testFuture();
//第二種,異步非阻塞
testFuture().then((value) {});
}
對于同步的future桥言,我們使用try-catch進(jìn)行異常捕獲
try {
await testFuture();
} catch(e){
print(e.toString());
}
對于異步的future萌踱,有兩種方式進(jìn)行異常捕獲
testFuture().then((value){
//成功回調(diào)
},onError: (_) {
//方式1,使用onError
}).catchError((e) {
//方式2号阿,使用catchError
}););
方式1:使用onError并鸵,onError優(yōu)先級大于catchError,因此當(dāng)catchError和onError同時存在時扔涧,會命中onError方法
方式2:使用catchError
分享一個catchError失敗的案例:
Future testFuture() {
throw AssertionError("assert error2");
}
//調(diào)用處
main() {
try {
testFuture().then((value) {}, onError(_){
print("onError error");
})
} catch (e) {
print("try-catch error");
}
}
運行發(fā)現(xiàn)园担,此時onError并沒有被命中,而是被try-catch捕獲了異常枯夜。我們又嘗試在testFuture方法后加上 asyhc 進(jìn)行修飾弯汰,聲明告知這是一個異步結(jié)果,此時onError會被命中湖雹∮缴粒或者,我們將 throw AssertionError("assert error2") 改為 return Future.error("assert error2") 摔吏, onError 也會被命中鸽嫂。