'dart:async'的函数`runZoned`的目的是什么?

18

1
此功能是为了弥补其他有用功能的缺失而添加的。只有在您需要(想要?)捕获无法修改的代码中的错误时才有用。也就是说,如果您想处理在异步操作中抛出未预期异常的代码,则它很有用。runZoned可以捕获这些未被观察到的异常,这些异常由于源代码中的错误原因而无法捕获。对我来说,最好不要使用会抛出未被观察到异常的代码,而是在runZoned环境中运行已知存在错误的代码。其他有用功能的缺失:async/await。 - mezoni
2
当编译器支持async/await操作时,它(或其他工具)可以检测异步操作源代码中的潜在错误。在这种情况下,它可以为程序员生成警告。如果程序是使用async/await操作编程约定编写的,并且不包含可能导致未观察到的异常的明显潜在错误,则通常不需要runZoned。实际上,runZoned是对异步代码中错过(未观察到)异常的“强制”陷阱,由于源代码编写不当而无法捕获。 - mezoni
1个回答

18

看一下这段代码:

import 'dart:async';

void main() {
  fineMethod().catchError((s) {}, test : (e) => e is String);
  badMethod().catchError((s) {}, test : (e) => e is String);
}

Future fineMethod() {
  return new Future(() => throw "I am fine");
}

Future badMethod() {
  new Future(() => throw "I am bad");
  return new Future(() => throw "I am fine");
}

输出

Unhandled exception:
I am bad

现在看一下这段代码:

import 'dart:async';

void main() {
  fineMethod().catchError((s) {}, test : (e) => e is String);

  runZoned(() {
    badMethod().catchError((s) {}, test : (e) => e is String);
  }, onError : (s) {
    print("It's not so bad but good in this also not so big.");
    print("Problem still exists: $s");
  });
}

Future fineMethod() {
  return new Future(() => throw "I am fine");
}

Future badMethod() {
  new Future(() => throw "I am bad");
  return new Future(() => throw "I am fine");
}

输出

It's not so bad but good in this also not so big.
Problem still exists: I am bad

如果可能的话,您应该严格避免使用badMethod

只有在不可能的情况下,您才可以暂时使用runZoned

此外,您可以使用runZoned来模拟sandboxed任务执行。

回答的更新版本:

import 'dart:async';

Future<void> main() async {
  try {
    await fineMethod();
  } catch (e) {
    log(e);
  }

  await runZonedGuarded(() async {
    try {
      await badMethod();
    } catch (e) {
      log(e);
    }
  }, (e, s) {
    print("========");
    print("Unhandled exception, handled by `runZonedGuarded`");
    print("$e");
    print("========");
  });
}

Future badMethod() {
  // Unhandled exceptions
  Future(() => throw "Bad method: bad1");
  Future(() => throw "Bad method: bad2");
  return Future(() => throw "Bad method: fine");
}

Future fineMethod() {
  return Future(() => throw "Fine method: fine");
}

void log(e) {
  print('Handled exception:');
  print('$e');
}

输出:

Handled exception:
Fine method: fine
========
Unhandled exception, handled by `runZonedGuarded`
Bad method: bad1
========
========
Unhandled exception, handled by `runZonedGuarded`
Bad method: bad2
========
Handled exception:
Bad method: fine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接