-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathTryWithEffect.cs
50 lines (43 loc) · 1.61 KB
/
TryWithEffect.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
// Copyright (c) TotalSoft.
// This source code is licensed under the MIT license.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace NBB.Core.Effects
{
public class TryWith
{
public class SideEffect<T> : ISideEffect<T>, IAmHandledBy<Handler<T>>
{
public Effect<T> InnerEffect { get; }
public Func<Exception, Effect<T>> ExceptionHandler { get; }
public SideEffect(Effect<T> innerEffect, Func<Exception, Effect<T>> exceptionHandler)
{
InnerEffect = innerEffect;
ExceptionHandler = exceptionHandler;
}
}
public class Handler<T> : ISideEffectHandler<SideEffect<T>, T>
{
private readonly IInterpreter _interpreter;
public Handler(IInterpreter interpreter)
{
_interpreter = interpreter;
}
public async Task<T> Handle(SideEffect<T> sideEffect, CancellationToken cancellationToken = default)
{
try {
return await _interpreter.Interpret(sideEffect.InnerEffect, cancellationToken);
}
catch (Exception ex){
var effect = sideEffect.ExceptionHandler.Invoke(ex);
return await _interpreter.Interpret(effect, cancellationToken);
}
}
}
public static SideEffect<T> From<T>(Effect<T> innerEffect, Func<Exception, Effect<T>> exceptionHandler)
{
return new(innerEffect, exceptionHandler);
}
}
}