Skip to content

Instantly share code, notes, and snippets.

@buzzySmile
Created October 13, 2020 17:02
Show Gist options
  • Save buzzySmile/8fa6b271bc3fe178018d58b144da3bec to your computer and use it in GitHub Desktop.
Save buzzySmile/8fa6b271bc3fe178018d58b144da3bec to your computer and use it in GitHub Desktop.
Exceptions processing in regular+future case
import 'dart:math';
class PoliceException implements Exception {
PoliceException({this.msg});
final String msg;
@override
String toString() => 'Police Raid {$msg}';
}
class RiskyDealer {
RiskyDealer(this.name);
final String name;
Future<String> dangerMove() async {
print('$name start hustle');
await Future.delayed(Duration(seconds: 1));
var rng = new Random();
if (rng.nextInt(4) == 0) {
throw PoliceException(msg: 'Dealer <$name> arrested');
}
if (rng.nextInt(3) == 0) {
return Future.error('$name was ripped of');
}
return '$name pushed some stuff';
}
}
void main() async {
List<RiskyDealer> mafia = [
RiskyDealer('[1]Rob'),
RiskyDealer('[2]Mike'),
RiskyDealer('[3]Carlos'),
RiskyDealer('[4]Walter'),
RiskyDealer('[5]Jesse'),
RiskyDealer('[6]Gomez'),
RiskyDealer('[7]Daniel'),
];
print('>>>Mafia starts deals\n');
try {
for (RiskyDealer dealer in mafia) {
await dealer
.dangerMove()
.then((result) => print('SUCCESS: $result'))
.catchError((fail) {
if (fail is PoliceException) {
print('FIASCO!!!');
throw fail;
}
print('FAILED: $fail');
});
await Future.delayed(Duration(seconds: 1), () => print('\n>next turn<'));
}
} on PoliceException catch (alarm) {
print(alarm);
print('\n>>>Mafia was unveiled!');
return;
}
print('\n>>>Mafia survives!');
}
@buzzySmile
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment