iivchenko / ShogunLib

Set of libraries with useful and reusable code like LINQ extension, Monads, event extensions and helpers, patterns etc.
MIT License
1 stars 0 forks source link

Add safe execution methods #16

Open iivchenko opened 8 years ago

iivchenko commented 8 years ago

I would like to have some very convenient methods which will execute any code, catch exception and do additional custom handling

In general this is not very interesting for me and I don't see profits and beauty. so lets wait for the passion ❗️

Branch with last idea https://github.com/iivchenko/ShogunLib/tree/release_0.2/issue_16

iivchenko commented 7 years ago

Idea 1

public static void SafeExecute(Action action)
{
    SafeExecute(action, e => { });
}

public static void SafeExecute(Action action, Action<Exception> errorHandler)
{
    try
    {
        action();
    }
    catch (Exception e)
    {
        errorHandler(e);
    }
}

public static bool TryExecute<TException>(Action action, out TException e);

Idea 2

// <copyright company="XATA">
//      Copyright (c) 2016 by Shogun, All Right Reserved
// </copyright>
// <author>Ivan Ivchenko</author>
// <email>iivchenko@live.com</email>

using System;
using NUnit.Framework;

namespace ShogunLib.Tests
{
    [TestFixture]
    public sealed class Sandbox
    {
        [Test]
        public void Test()
        {
            //new Action<string>(name => { Console.WriteLine("HI");})
            //    .ToSave()
            //    .AddExceptionHandler<ArgumentNullException>(e => Console.WriteLine(e)))
            //    .SetExceptionPolicy(All)
            //    .Execute("My");

            Safe
                .CreateNew()
                .AddExceptionHandler<ArgumentNullException>(e => Console.WriteLine(e))
                .AddExceptionHandler<ArgumentNullException>(e => Console.WriteLine(e))
                .Execute(() => Console.WriteLine("Error prone code!!"));
        }
    }
}

// <copyright company="XATA">
//      Copyright (c) 2016 by Shogun, All Right Reserved
// </copyright>
// <author>Ivan Ivchenko</author>
// <email>iivchenko@live.com</email>

namespace ShogunLib.Tests
{
    public class Safe
    {
        private Safe()
        {
        }

        public static Safe CreateNew()
        {
            return new Safe();
        }
    }
}

// <copyright company="XATA">
//      Copyright (c) 2016 by Shogun, All Right Reserved
// </copyright>
// <author>Ivan Ivchenko</author>
// <email>iivchenko@live.com</email>

using System;

namespace ShogunLib.Tests
{
    public static class SafeExtensions
    {
        public static Safe AddExceptionHandler<TException>(this Safe source, Action<TException> handler)
            where TException : Exception
        {
            source.Exceptions[typeof (TException)].Add(handler);

            return source;
        }

        public static void Execute(this Safe source, Action action)
        {
            source.Execute(action);
        }
    }
}