forked from Mr-Sunglasses/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfuture-error-test-in-flutter.dart
54 lines (45 loc) · 1.29 KB
/
future-error-test-in-flutter.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
// Want to support my work 🤝? https://buymeacoffee.com/vandad
import 'dart:developer' as dev show log;
@immutable
abstract class UserException implements Exception {}
class InvalidUserNameException extends UserException {}
class InvalidUserAgeException extends UserException {}
@immutable
class User {
final String name;
final int age;
User({required this.name, required this.age}) {
if (!name.contains(RegExp(r'^[a-z ]+$'))) {
throw InvalidUserNameException();
} else if (age < 0 || age > 130) {
throw InvalidUserAgeException();
}
}
const User.anonymous()
: name = 'Anonymous User',
age = 0;
}
Future<User> getAsyncUser() => Future.delayed(
const Duration(seconds: 1),
() => User(name: 'Foo', age: 20),
);
void testIt() async {
final user = await getAsyncUser()
.catchError(
handleInvalidUsernameException,
test: (e) => e is InvalidUserNameException,
)
.catchError(
handleInvalidAgeException,
test: (e) => e is InvalidUserAgeException,
);
dev.log(user.toString());
}
User handleInvalidUsernameException(Object? e) {
dev.log(e.toString());
return const User.anonymous();
}
User handleInvalidAgeException(Object? e) {
dev.log(e.toString());
return const User.anonymous();
}