存在由dart:async
提供的特殊功能runZoned
.文件在这里:https://api.dartlang.org/docs/channels/stable/latest/dart_async.html#runZoned
我不确定这个功能的用途,我们什么时候需要它,以及如何正确使用它?
存在由dart:async
提供的特殊功能runZoned
.文件在这里:https://api.dartlang.org/docs/channels/stable/latest/dart_async.html#runZoned
我不确定这个功能的用途,我们什么时候需要它,以及如何正确使用它?
请看下面的代码:
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
个任务的执行.
Updated version of the answer:个
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