-
-
Save Adrek/e2ab801177144d6e4a967516471ab026 to your computer and use it in GitHub Desktop.
[Dart] Try-catch in a while loop that retries a code after a specific duration time for a specific number of times
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'package:flutter/foundation.dart'; | |
void main() { | |
FutureOr<void> tryCatchLoop({ | |
@required FutureOr<void> Function() code, | |
@required FutureOr<void> Function(dynamic error) onError, | |
Duration duration = const Duration(milliseconds: 200), int limitTimes = 5 | |
}) async { | |
int count = 0; | |
bool hasError = false; | |
dynamic error; | |
do { | |
try { | |
await code(); | |
count = limitTimes; | |
} catch (catched) { | |
await Future.delayed(duration, () => count++); | |
print(count); // this line shows you how the function works, delete it in production | |
if (count == limitTimes) { | |
hasError = true; | |
error = catched; | |
} | |
} | |
} while (count != limitTimes); | |
if (hasError) { | |
await onError(error); | |
} | |
} | |
tryCatchLoop( | |
code: () { | |
throw 'Premeditated error'; | |
}, | |
onError: (error) { | |
print("Error: " + error.toString()); | |
}, | |
duration: Duration(seconds: 1), | |
limitTimes: 10 | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment