dart - 是否有异步错误的全局处理程序?

标签 dart

在老式的同步代码中,您始终可以通过将源代码封装到一个大的 try catch block 中来确保您的程序不会完全崩溃,例如:

try {
  // Some piece of code
} catch (e) {
  logger.log(e); // log error
}

但是在 Dart 中,当使用 FutureStream 时,就没那么容易了。以下示例将使您的应用程序完全崩溃

try {
  doSomethingAsync().then((result) => throw new Exception());
} catch (e) {
  logger.log(e);
}

try-catch block 中是否有代码并不重要。

是的,你总是可以使用Future.catchError,不幸的是,如果你使用第三方库函数,这对你没有帮助,如下所示:

void someThirdPartyDangerousMethod() {
  new Future.value(true).then((result) => throw new Exception());
}

try {
  // we can't use catchError, because this method does not return Future
  someThirdPartyDangerousMethod(); 
} catch (e) {
  logger.log(e);
}

有没有办法防止不可信代码破坏整个应用程序?像全局错误处理程序之类的东西?

最佳答案

您可以使用全新的区域。只需在 Zone 中运行您的代码并为其附加错误处理程序。

void someThirdPartyDangerousMethod() {
  new Future.value(true).then((result) => throw new Exception());
}

runZoned(() {
  // we can't use catchError, because this method does not return Future
  someThirdPartyDangerousMethod(); 
}, onError: (e) {
  logger.log(e);
});

这应该会按预期工作!每个 Uncaught Error 都将由 onError 处理程序处理。有一点不同于使用 try-catch block 的经典示例。 Zone 内运行的代码在发生错误时不会停止,错误由 onError 回调处理,应用程序继续运行。

关于dart - 是否有异步错误的全局处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20182550/

相关文章:

google-maps - form.currentstate.validate()失败- flutter

mobile - 在 pdf 查看器上显示/隐藏选项栏

flutter - 在main.dart文件中添加提供程序的更好方法

dart - 如何在 VSCode 中重命名 dart 文件?

firebase - Flutter/Dart/FireStore 查询报错: NoSuchMethod

android - 函数 'Stream<User?>' 无法返回类型为 'user' 的值,因为它在 flutter 中的返回类型为 'Stream<User>'

flutter - Dart/Flutter中的全局变量

flutter - flutter -垂直对齐按钮

file - 与其他应用程序共享文件/文本并成功回调

dart - 如何使用 Dart 删除尾随零