在老式的同步代码中,您始终可以通过将源代码封装到一个大的 try catch block 中来确保您的程序不会完全崩溃,例如:
try {
// Some piece of code
} catch (e) {
logger.log(e); // log error
}
但是在 Dart 中,当使用 Future
和 Stream
时,就没那么容易了。以下示例将使您的应用程序完全崩溃
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/