当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。