Dart中的catchError捕获顺序
生活随笔
收集整理的這篇文章主要介紹了
Dart中的catchError捕获顺序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
先貼一下該方法的源碼:
/*** 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)}); 復制代碼翻譯一下主要的意思,就是這個catchError方法可以捕獲其他Futrue的異常信息,如果重寫了test方法,test返回true就可以在catchError的onError方法里捕獲到異常,如果test返回false,就把該異常繼續拋出而不會在catchError方法里被捕獲,如果不寫test默認實現一個返回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); } 復制代碼如果是上面的代碼,會輸出
test error catchError error 復制代碼因為//3這行返回了true,所以會在第一個catchError里被捕獲。 如果//4不注釋了,把//3注釋,那么第一個catchError不能捕獲該異常,該異常會繼續拋出,然后在第二個catchError里被捕獲。具體的可自行測試。
還有就是用whenComplete方法的時候,不是所有then都執行完再執行whenComplete方法,而是then、catchError、whenComplete這些方法會按照順序(除非中途有異常會進入下一個catchError)執行,這一點和rxjava+retrofit不一樣,原生開發請知悉。
總結
以上是生活随笔為你收集整理的Dart中的catchError捕获顺序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 硬件监控-网络设备
- 下一篇: 【运维安全】- 总结