考虑使用
异步-等待
捕捉“最后一步”中的错误。这个答案
https://github.com/flutter/flutter/issues/22734
帮了我很多忙。
下面是我从一个我不记得的源代码中得到的代码片段,它帮助我理解如何正确地使用
未来
我对它做了一些修改,以测试我的确切情况(补充
主4()
和
DivideFullAsyncNested()。
功能)。希望有帮助。
// SO 29378453
import 'dart:async';
import 'package:login_app/constants.dart';
main() {
// fails
main1();
main2();
main3();
main4();
}
Future<double> divide(int a, b) {
// this part is still sync
if (b == 0) {
throw new Exception('Division by zero divide non-async');
}
// here starts the async part
return new Future.value(a / b);
}
Future<double> divideFullAsync(int a, b) {
return new Future(() {
if (b == 0) {
throw new Exception('Division by zero full async');
}
return new Future.value(a / b);
// or just
// return a / b;
});
}
Future<double> divideFullAsyncNested() {
return divideFullAsync(7, 8).then(
(val) {
return divideFullAsync(5, 0).then(
(val2) {
return Future(() {
if (val2 == 1) {
throw Exception('Innermost: Result not accepted exception.');
}
return val2;
});
},
).catchError((err) => throw Exception('Inner: $err'));
},
).catchError((err) => throw Exception('Outter: $err'));
}
//Future<double> divideFullAsyncNested() {
// return divideFullAsync(9, 9).then(
// (val) {
// return Future(
// () {
// if (val == 1) {
// throw Exception('Result not accepted exception.');
// }
// return val;
// },
// );
// },
// ).catchError((err) => throw Exception(err.toString()));
//}
// async error handling doesn't catch sync exceptions
void main1() async {
try {
// divide(1, 0).then((result) => print('(1) 1 / 0 = $result')).catchError(
// (error) => print('(1)Error occured during division: $error'));
var result = await divide(1, 0);
print('(1) 1 / 0 = $result');
} catch (ex) {
print('(1.1)Error occured during division: ${ex.toString()}');
}
}
// async error handling catches async exceptions
void main2() {
divideFullAsync(1, 0)
.then((result) => print('(2) 1 / 0 = $result'))
.catchError(
(error) => print('(2) Error occured during division: $error'));
}
// async/await allows to use try/catch for async exceptions
main3() async {
try {
await divideFullAsync(1, 0);
print('3');
} catch (error) {
print('(3) Error occured during division: $error');
}
}
main4() async {
// try {
// await divideFullAsyncNested();
// } on Exception catch (e) {
// print("(4) ${e.toString().replaceAll('Exception:', '').trimLeft().trimRight()}");
// }
try {
divideFullAsyncNested()
.then((v) => print(v))
.catchError((err) => print(Constants.refinedExceptionMessage(err)));
} on Exception catch (e) {
print("(4) ${Constants.refinedExceptionMessage(e)}");
}
}