是否存在异步错误的全局处理程序?

Sam*_*pak 3 dart

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

try {
  // Some piece of code
} catch (e) {
  logger.log(e); // log error
}
Run Code Online (Sandbox Code Playgroud)

但是在Dart中,当使用Futures和Streams时,它并不那么容易.以下示例将完全崩溃您的应用程序

try {
  doSomethingAsync().then((result) => throw new Exception());
} catch (e) {
  logger.log(e);
}
Run Code Online (Sandbox Code Playgroud)

不要紧,你有里面的代码try- catch块.

是的,您可以随时使用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);
}
Run Code Online (Sandbox Code Playgroud)

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

Sam*_*pak 5

你可以使用全新Zone的.只需在其中运行代码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);
});
Run Code Online (Sandbox Code Playgroud)

这应该按预期工作!每个未捕获的错误都将由处理onError程序处理.有一点与使用try- catchblock 的经典示例不同.Zone发生错误时,内部运行的代码不会停止,错误由onError回调处理,应用程序继续运行.