~ruther/NosSmooth.Local

ref: d5b3c3ffb40aa86f582a0f26fc0376caa245f220 NosSmooth.Local/src/Core/NosSmooth.LocalBinding/OptionalUtilities.cs -rw-r--r-- 1.9 KiB
d5b3c3ff — Rutherther Merge pull request #18 from Rutherther/feat/optional-binding 2 years ago
                                                                                
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
//
//  OptionalUtilities.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Remora.Results;

namespace NosSmooth.LocalBinding;

/// <summary>
/// A utilities that work with members that may not be present or may throw an exception.
/// </summary>
public static class OptionalUtilities
{
    /// <summary>
    /// Tries to get value from the function, capturing an exception into Result.
    /// </summary>
    /// <param name="get">The function to obtain the value from.</param>
    /// <typeparam name="T">The type of the value.</typeparam>
    /// <returns>The value, or exception error if an exception has been thrown.</returns>
    public static Result<T> TryGet<T>(Func<T> get)
    {
        try
        {
            return get();
        }
        catch (Exception e)
        {
            return e;
        }
    }

    /// <summary>
    /// Tries to get value from the function, capturing an exception into Result.
    /// </summary>
    /// <param name="get">The function to obtain the value from.</param>
    /// <typeparam name="T">The type of the value.</typeparam>
    /// <returns>The value, or exception error if an exception has been thrown.</returns>
    public static Result<T> TryIGet<T>(Func<Result<T>> get)
    {
        try
        {
            return get();
        }
        catch (Exception e)
        {
            return e;
        }
    }

    /// <summary>
    /// Tries to execute an action.
    /// </summary>
    /// <param name="get">The action.</param>
    /// <returns>A result, successful if no exception has been thrown.</returns>
    public static Result Try(Action get)
    {
        try
        {
            get();
            return Result.FromSuccess();
        }
        catch (Exception e)
        {
            return e;
        }
    }
}
Do not follow this link