日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

Dart中的catchError捕获顺序

發(fā)布時間:2025/7/25 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Dart中的catchError捕获顺序 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

先貼一下該方法的源碼:

/*** Handles errors emitted by this [Future].** This is the asynchronous equivalent of a "catch" block.** Returns a new [Future] that will be completed with either the result of* this future or the result of calling the `onError` callback.** If this future completes with a value,* the returned future completes with the same value.** If this future completes with an error,* then [test] is first called with the error value.** If `test` returns false, the exception is not handled by this `catchError`,* and the returned future completes with the same error and stack trace* as this future.** If `test` returns `true`,* [onError] is called with the error and possibly stack trace,* and the returned future is completed with the result of this call* in exactly the same way as for [then]'s `onError`.** If `test` is omitted, it defaults to a function that always returns true.* The `test` function should not throw, but if it does, it is handled as* if the `onError` function had thrown.** 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.* See the description on [Future].*/// The `Function` below stands for one of two types:// - (dynamic) -> FutureOr<T>// - (dynamic, StackTrace) -> FutureOr<T>// Given that there is a `test` function that is usually used to do an// `isCheck` we should also expect functions that take a specific argument.// Note: making `catchError` return a `Future<T>` in non-strong mode could be// a breaking change.Future<T> catchError(Function onError, {bool test(Object error)}); 復(fù)制代碼

翻譯一下主要的意思,就是這個catchError方法可以捕獲其他Futrue的異常信息,如果重寫了test方法,test返回true就可以在catchError的onError方法里捕獲到異常,如果test返回false,就把該異常繼續(xù)拋出而不會在catchError方法里被捕獲,如果不寫test默認(rèn)實現(xiàn)一個返回true的test方法,注意catchError只能捕獲Future的異常,而不能捕獲同步代碼的異常,測試代碼如下:

import 'dart:async';Future testFutureError() {return new Future(() {throw "error";//1 // return "abc";//2}); }main() {testFutureError().then((value) {print("then " + value);}).catchError((e) {print("catchError " + e);}, test: (Object o) {print("test " + o);return true;//3 // return false;//4}).catchError((e) {print("catchError2 " + e);}, test: (_) => true); } 復(fù)制代碼

如果是上面的代碼,會輸出

test error catchError error 復(fù)制代碼

因為//3這行返回了true,所以會在第一個catchError里被捕獲。 如果//4不注釋了,把//3注釋,那么第一個catchError不能捕獲該異常,該異常會繼續(xù)拋出,然后在第二個catchError里被捕獲。具體的可自行測試。

還有就是用whenComplete方法的時候,不是所有then都執(zhí)行完再執(zhí)行whenComplete方法,而是then、catchError、whenComplete這些方法會按照順序(除非中途有異常會進(jìn)入下一個catchError)執(zhí)行,這一點和rxjava+retrofit不一樣,原生開發(fā)請知悉。

總結(jié)

以上是生活随笔為你收集整理的Dart中的catchError捕获顺序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。