-
Notifications
You must be signed in to change notification settings - Fork 0
/
error_or_example.dart
96 lines (84 loc) · 2.18 KB
/
error_or_example.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import 'dart:async';
import 'dart:math';
import 'package:error_or/error_or.dart';
String maybeThrows() {
if (Random().nextBool() == false) {
throw Exception('Error');
}
return 'Success';
}
ErrorOr<String> maybeErrorSync() {
if (Random().nextBool() == false) {
return ErrorOr.error(Exception('Error'));
}
return ErrorOr.value('Success');
}
final delay = Duration(milliseconds: 400);
Future<String> getValueOrThrows() async {
await Future.delayed(delay);
return maybeThrows();
}
Future<ErrorOr<String>> getValueOrError() async {
await Future.delayed(delay);
return ErrorOr.wrap(maybeThrows);
}
Future<void> errorHandlingWithThenAndCatchError() async {
print('* Error handling with then and catchError');
final completer = Completer();
getValueOrThrows().then((String value) {
print(value);
}).catchError((e) {
print(e);
}).whenComplete(() {
print('');
completer.complete();
});
return completer.future;
}
Future<void> errorHandlingWithAwaitAndTryCatch() async {
print('* Error handling with await and try/catch');
try {
final String value = await getValueOrThrows();
print(value);
} catch (e) {
print(e);
}
print('');
}
Future<void> errorHandlingWithErrorOr() async {
print('* Error handling with ErrorOr');
final ErrorOr<String> errorOr = await getValueOrError();
if (errorOr.hasError) {
print(errorOr.error);
} else {
print(errorOr.value);
}
print('');
}
void errorHandlingWithErrorOrSync() {
print('* Error handling with ErrorOr sync');
final ErrorOr<String> errorOr = maybeErrorSync();
if (errorOr.hasError) {
print(errorOr.error);
} else {
print(errorOr.value);
}
print('');
}
Future<void> errorHandlingWithErrorOrTypeError() async {
print('* Error handling with ErrorOr throws ErrorOrTypeError');
try {
final ErrorOr<String> errorOr = await getValueOrError();
print(errorOr.value);
} on ErrorOrTypeError catch (e) {
print(e.message);
}
print('');
}
void main() async {
await errorHandlingWithThenAndCatchError();
await errorHandlingWithAwaitAndTryCatch();
await errorHandlingWithErrorOr();
errorHandlingWithErrorOrSync();
await errorHandlingWithErrorOrTypeError();
}