This repository has been archived by the owner on Jun 9, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 260
/
Copy pathresult.dart
65 lines (52 loc) · 1.48 KB
/
result.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
import 'package:app/data/app_error.dart';
import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'result.freezed.dart';
@freezed
abstract class Result<T> with _$Result<T> {
const Result._();
const factory Result.success({required T data}) = Success<T>;
const factory Result.failure({required AppError error}) = Failure<T>;
static Result<T> guard<T>(T Function() body) {
try {
return Result.success(data: body());
} on Exception catch (e) {
return Result.failure(error: AppError(e));
}
}
static Future<Result<T>> guardFuture<T>(Future<T> Function() future) async {
try {
return Result.success(data: await future());
} on Exception catch (e) {
return Result.failure(error: AppError(e));
}
}
bool get isSuccess => when(success: (data) => true, failure: (e) => false);
bool get isFailure => !isSuccess;
void ifSuccess(Function(T data) body) {
maybeWhen(
success: (data) => body(data),
orElse: () {
// no-op
},
);
}
void ifFailure(Function(AppError e) body) {
maybeWhen(
failure: (e) => body(e),
orElse: () {
// no-op
},
);
}
T get dataOrThrow {
return when(
success: (data) => data,
failure: (e) => throw e,
);
}
}
extension ResultObjectExt<T> on T {
Result<T> get asSuccess => Result.success(data: this);
Result<T> asFailure(Exception e) => Result.failure(error: AppError(e));
}