-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathTryExceptionHandling.cs
58 lines (52 loc) · 2.15 KB
/
TryExceptionHandling.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
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace FuncSharp.Examples;
public enum NetworkOperationError
{
ServerError,
ConnectionTimedOut,
NetworkIssues
}
public static class Api
{
public static Try<int, NetworkOperationError> GetNumber()
{
// This method serves as an example use-case for handling value of ITries, instead of random next, there should be some network call.
return PerformNetworkOperation(_ => new Random().Next());
}
public static Try<int, NetworkOperationError> DoubleNumber(int value)
{
// This method serves as an example use-case for handling value of ITries, instead of multiplication, there should be some network call.
return PerformNetworkOperation(_ => value * 2);
}
private static Try<T, NetworkOperationError> PerformNetworkOperation<T>(Func<Unit, T> operation)
{
var connectionErrorStatuses = new[]
{
WebExceptionStatus.ConnectFailure,
WebExceptionStatus.ConnectionClosed,
WebExceptionStatus.SecureChannelFailure,
WebExceptionStatus.NameResolutionFailure
};
try
{
return Try.Success<T, NetworkOperationError>(operation(Unit.Value));
}
catch (TaskCanceledException)
{
return Try.Error<T, NetworkOperationError>(NetworkOperationError.ConnectionTimedOut);
}
catch (WebException e) when (e.Response.As<HttpWebResponse>().Map(r => (int)r.StatusCode > 500 && (int)r.StatusCode < 599).GetOrFalse())
{
return Try.Error<T, NetworkOperationError>(NetworkOperationError.ServerError);
}
catch (WebException e) when (connectionErrorStatuses.Contains(e.Status))
{
return Try.Error<T, NetworkOperationError>(NetworkOperationError.NetworkIssues);
}
// Notice that general Exception is not handled. We're handling the exceptions we expect, so the signature makes sense.
// The purpose of Try is not covering every exception. But that methods should show what are the expected outputs and make the call site handle all of them.
}
}