consider this code:
EXAMPLE A:
Future<void> fakeCall() async {
await Future.delayed(const Duration(milliseconds: 300), () {
throw MyError('myException');
});
}
Future<void> fetch() async {
Future<void> testFuture = fakeCall();
testFuture.whenComplete(() {
print('when completed');
});
testFuture.catchError((e) {
print('on error');
});
return testFuture;
}
void main() async {
try{
await fetch();
}on MyError catch(e){
//getting here but one still leaks!!
}
}
when calling await fetch() I expect only catchError to be called. but the Error somehow leaks, so basically two were thrown...one caught by catchError and one is leaked outside as an unhandled error.
but when using it the proposed way (chained one after the other):
EXAMPLE B:
Future<void> fakeCall() async {
await Future.delayed(const Duration(milliseconds: 300), () {
throw MyError('myException');
});
}
Future<void> fetch() async {
Future<void> testFuture = fakeCall().whenComplete(() {
print('when completed');
}).catchError((e) {
print('on error');
});
return testFuture;
}
void main() async {
try{
await fetch();
}on MyError catch(e){
//getting here and nothing leaks!!
}
}
No error leaking occurs. It just left me very curious, can someone explain why writing it in the first way makes the error to leak?
update
originally I forgot to add try/catch around the fetch function, so you might think the error leaked for this reason. but notice, the error still leaks when not chaining the onError properly (first example)