-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathparameterized_error.dart
More file actions
62 lines (53 loc) · 2.08 KB
/
parameterized_error.dart
File metadata and controls
62 lines (53 loc) · 2.08 KB
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
/// {@template ParameterizedError}
/// Error for when the provided value(s) didn't match the function arguments
/// types or count.
/// {@endtemplate}
class ParameterizedError extends Error {
/// {@macro ParameterizedError}
ParameterizedError(this.message);
/// Creates a [ParameterizedError] from a [TypeError].
/// When arguments types don't match the function arguments types.
factory ParameterizedError.forTypeError(List<dynamic> value, Function body) {
final bodyClosure = extractFunctionArgumentsSignature(body.toString());
return ParameterizedError(
"Provided value(s) didn't match the function arguments types.\n"
'Test values: $value\n'
'Provided types: '
'(${value.map((e) => e.runtimeType).join(', ')})\n'
'Expected types: ($bodyClosure)',
);
}
/// Creates a [ParameterizedError] from a [TypeError].
/// When arguments count don't match the function arguments count.
factory ParameterizedError.fromNoSuchMethodError(
NoSuchMethodError e,
List<dynamic> value,
) {
final bodyClosure = extractFunctionArgumentsSignature(e.toString());
final positionalArgumentsCount = ','.allMatches(bodyClosure).length + 1;
return ParameterizedError(
"Provided value(s) didn't match the function arguments count.\n"
'Amount of provided values: ${value.length}\n'
'Expected function arguments: $positionalArgumentsCount\n'
'Test values: $value\n'
'Provided types: '
'(${value.map((e) => e.runtimeType).join(', ')})\n'
'Expected types: ($bodyClosure)',
);
}
/// Error message.
final String message;
/// Helper function to extract the function arguments signature from
/// Exception string.
static String extractFunctionArgumentsSignature(String body) {
const closure = 'Closure: (';
final closureIndex = body.indexOf(closure);
final endIndex = body.indexOf(')', closureIndex);
final bodyClosure = body.substring(closureIndex + closure.length, endIndex);
return bodyClosure.replaceAll(RegExp('<(.*)>'), '');
}
@override
String toString() {
return message;
}
}