當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Dart runZonedGuarded用法及代碼示例

dart:async 庫中runZonedGuarded 函數的用法介紹如下。

用法:

@Since("2.8")   

R? runZonedGuarded<R>(
   R body(
),    
   void onError(
   Object error,    
   StackTrace stack   
),    
   {Map<Object?, Object?>? zoneValues,    
   ZoneSpecification? zoneSpecification}   
)

在自己的錯誤區域中運行body

基於 zoneSpecificationzoneValues 使用 Zone.fork 創建一個新區域,然後在該區域中運行 body 並返回結果。

onError 函數用於 both 通過覆蓋 zoneSpecification 中的 ZoneSpecification.handleUncaughtError 來處理異步錯誤,如果有的話, and 以處理由調用 body 同步引發的錯誤。

如果在 body 中同步發生錯誤,則在 onError 處理程序中引發對 runZonedGuarded 的調用會引發該錯誤,否則對 runZonedGuarded 的調用將返回 null

該區域將始終為error-zone。

錯誤本身永遠不會跨越error-zone 邊界。嘗試跨越error-zone 邊界的錯誤被視為在其原始錯誤區域中未被捕獲。

var future = Future.value(499);
runZonedGuarded(() {
  var future2 = future.then((_) { throw "error in first error-zone"; });
  runZonedGuarded(() {
    var future3 = future2.catchError((e) { print("Never reached!"); });
  }, (e, s) { print("unused error handler"); });
}, (e, s) { print("catches error of first error-zone."); });

例子:

runZonedGuarded(() {
  Future(() { throw "asynchronous error"; });
}, (e, s) => print(e));  // Will print "asynchronous error".

可以通過在新區域中重新拋出錯誤來手動將錯誤從一個錯誤區域傳遞到另一個錯誤區域。如果onError 拋出,該錯誤將發生在調用runZoned 的原始區域中。

相關用法


注:本文由純淨天空篩選整理自dart.dev大神的英文原創作品 runZonedGuarded<R> function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。