-
Notifications
You must be signed in to change notification settings - Fork 0
/
Result.cs
133 lines (118 loc) · 2.6 KB
/
Result.cs
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
using System;
namespace TagsCloudVisualization
{
public class None
{
private None()
{
}
}
public struct Result<T>
{
public Result(string error, T value = default(T))
{
Error = error;
Value = value;
}
public static implicit operator Result<T>(T v)
{
return Result.Ok(v);
}
public string Error { get; }
internal T Value { get; }
public T GetValueOrThrow()
{
if (IsSuccess) return Value;
throw new InvalidOperationException($"No value. Only Error {Error}");
}
public bool IsSuccess => Error == null;
}
public static class Result
{
public static Result<T> AsResult<T>(this T value)
{
return Ok(value);
}
public static Result<T> Ok<T>(T value)
{
return new Result<T>(null, value);
}
public static Result<None> Ok()
{
return Ok<None>(null);
}
public static Result<T> Fail<T>(string e)
{
return new Result<T>(e);
}
public static Result<T> Of<T>(Func<T> f, string error = null)
{
try
{
return Ok(f());
}
catch (Exception e)
{
return Fail<T>(error ?? e.Message);
}
}
public static Result<None> OfAction(Action f, string error = null)
{
try
{
f();
return Ok();
}
catch (Exception e)
{
return Fail<None>(error ?? e.Message);
}
}
public static Result<TOutput> Then<TInput, TOutput>(
this Result<TInput> input,
Func<TInput, TOutput> continuation)
{
return input.Then(inp => Of(() => continuation(inp)));
}
public static Result<None> Then<TInput, TOutput>(
this Result<TInput> input,
Action<TInput> continuation)
{
return input.Then(inp => OfAction(() => continuation(inp)));
}
public static Result<None> Then<TInput>(
this Result<TInput> input,
Action<TInput> continuation)
{
return input.Then(inp => OfAction(() => continuation(inp)));
}
public static Result<TOutput> Then<TInput, TOutput>(
this Result<TInput> input,
Func<TInput, Result<TOutput>> continuation)
{
return input.IsSuccess
? continuation(input.Value)
: Fail<TOutput>(input.Error);
}
public static Result<TInput> OnFail<TInput>(
this Result<TInput> input,
Action<string> handleError)
{
if (!input.IsSuccess) handleError(input.Error);
return input;
}
public static Result<TInput> ReplaceError<TInput>(
this Result<TInput> input,
Func<string, string> replaceError)
{
if (input.IsSuccess) return input;
return Fail<TInput>(replaceError(input.Error));
}
public static Result<TInput> RefineError<TInput>(
this Result<TInput> input,
string errorMessage)
{
return input.ReplaceError(err => errorMessage + ". " + err);
}
}
}