TryCatchFinallyProcessHelper


namespace Test
{
    using Microshaoft;
    using System;
    using System.Threading.Tasks;
    class Program
    {
        static void Main(string[] args)
        {
            //string s = await Download("http://msdn.microsoft.com");
            using (var foo = new Foo())
            {
                try
                {
                    throw new Exception();
                    int i = 0;
                    int r = GetNumber(3);
                    //i /= i;
                    //throw new DivideByZeroException();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
                TryCatchFinallyProcessHelper.TryProcessCatchFinally
                    (
                        true
                        //false
                        , () =>
                        {
                            throw new Exception();
                            int ii = 0;
                            //int rr = GetNumber(3);
                            ii /= ii;
                            //throw new DivideByZeroException();
                        }
                        , false
                        , (x) =>
                        {
                            Console.WriteLine(x.ToString());
                            //throw new Exception("ReThrow Exception OnCaught", x);
                            return true;
                        }
                        , (x, y) =>
                        {
                            if (x)
                            {
                                Console.WriteLine("=======================finally: " + x.ToString());
                            }
                        }
                    );
            }
            Console.ReadLine();
        }
        static int GetNumber(int index)
        {
            int[] nums = { 300, 600, 900 };
            //if (index >= nums.Length)
            //{
            //    throw new IndexOutOfRangeException();
            //}
            int r = nums[index];
            return r;
        }
        public static async Task<string> DownloadAsync(string url)
        {
            return
                await
                    TryCatchFinallyProcessHelper
                        .TryProcessCatchFinallyAsync
                            (
                                true
                                , async
                                    () =>
                                {
                                    //var httpClient = new HttpClient();
                                    Task<string> task = null; //= httpClient.GetStringAsync(url);
                                    string s = await task;
                                    //int exampleInt = contents.Length; 
                                    return s;
                                }
                            );
        }
    }
}
namespace Microshaoft
{
    using System;
    class Foo : IDisposable
    {
        public void Dispose()
        {
            //Console.ReadLine();
            Console.WriteLine("Disposing");
            //throw new NotImplementedException();
        }
    }
}
namespace Microshaoft
{
    using System;
    using System.Diagnostics;
    using System.Reflection;
    using System.Threading.Tasks;
    public static class TryCatchFinallyProcessHelper
    {
        public static async Task<T> TryProcessCatchFinallyAsync<T>
                                    (
                                        bool needTry
                                        , Func<Task<T>> onTryProcessFunc
                                        , bool reThrowException = false
                                        , Func<Exception, bool> onCaughtExceptionProcessFunc = null
                                        , Action<bool, Exception> onFinallyProcessAction = null
                                    )
        {
            T r = default(T);
            //if (onTryProcessAction != null)
            {
                if (needTry)
                {
                    Exception exception = null;
                    var caughtException = false;
                    try
                    {
                        r = await onTryProcessFunc();
                        return r;
                    }
                    catch (Exception e)
                    {
                        caughtException = true;
                        exception = e;
                        var currentCalleeMethod = MethodInfo.GetCurrentMethod();
                        var currentCalleeType = currentCalleeMethod.DeclaringType;
                        StackTrace stackTrace = new StackTrace();
                        StackFrame stackFrame = stackTrace.GetFrame(1);
                        var callerMethod = stackFrame.GetMethod();
                        var callerType = callerMethod.DeclaringType;
                        var frame = (stackTrace.FrameCount > 1 ? stackTrace.FrameCount - 1 : 1);
                        stackFrame = stackTrace.GetFrame(frame);
                        var originalCallerMethod = stackFrame.GetMethod();
                        var originalCallerType = originalCallerMethod.DeclaringType;
                        var innerExceptionMessage = string.Format
                                (
                                    "Rethrow caught [{1}] Exception{0} at Callee Method: [{2}]{0} at Caller Method: [{3}]{0} at Original Caller Method: [{4}]"
                                    , "\r\n\t"
                                    , e.Message
                                    , string.Format("{1}{0}{2}", "::", currentCalleeType, currentCalleeMethod)
                                    , string.Format("{1}{0}{2}", "::", callerType, callerMethod)
                                    , string.Format("{1}{0}{2}", "::", originalCallerType, originalCallerMethod)
                                );
                        Console.WriteLine(innerExceptionMessage);
                        if (onCaughtExceptionProcessFunc != null)
                        {
                            reThrowException = onCaughtExceptionProcessFunc(e);
                        }
                        if (reThrowException)
                        {
                            throw
                                new Exception
                                        (
                                            innerExceptionMessage
                                            , e
                                        );
                        }
                        return r;
                    }
                    finally
                    {
                        if (onFinallyProcessAction != null)
                        {
                            onFinallyProcessAction(caughtException, exception);
                        }
                    }
                }
                else
                {
                    return await onTryProcessFunc();
                }
            }
        }
        public static void TryProcessCatchFinally
                                    (
                                        bool needTry
                                        , Action onTryProcessAction
                                        , bool reThrowException = false
                                        , Func<Exception, bool> onCaughtExceptionProcessFunc = null
                                        , Action<bool, Exception> onFinallyProcessAction = null
                                    )
        {
            if (onTryProcessAction != null)
            {
                if (needTry)
                {
                    Exception exception = null;
                    var caughtException = false;
                    try
                    {
                        onTryProcessAction();
                    }
                    catch (Exception e)
                    {
                        caughtException = true;
                        exception = e;
                        var currentCalleeMethod = MethodInfo.GetCurrentMethod();
                        var currentCalleeType = currentCalleeMethod.DeclaringType;
                        StackTrace stackTrace = new StackTrace(e, true);
                        StackFrame stackFrame = stackTrace.GetFrame(1);
                        var callerMethod = stackFrame.GetMethod();
                        var callerType = callerMethod.DeclaringType;
                        var frame = (stackTrace.FrameCount > 1 ? stackTrace.FrameCount - 1 : 1);
                        stackFrame = stackTrace.GetFrame(frame);
                        var originalCallerMethod = stackFrame.GetMethod();
                        var originalCallerType = originalCallerMethod.DeclaringType;
                        var innerExceptionMessage = string.Format
                                (
                                    "Rethrow caught [{1}] Exception{0} at Callee Method: [{2}]{0} at Caller Method: [{3}]{0} at Original Caller Method: [{4}]"
                                    , "\r\n\t"
                                    , e.Message
                                    , string.Format("{1}{0}{2}", "::", currentCalleeType, currentCalleeMethod)
                                    , string.Format("{1}{0}{2}", "::", callerType, callerMethod)
                                    , string.Format("{1}{0}{2}", "::", originalCallerType, originalCallerMethod)
                                );
                        //Console.WriteLine(innerExceptionMessage);
                        if (onCaughtExceptionProcessFunc != null)
                        {
                            reThrowException = onCaughtExceptionProcessFunc(e);
                        }
                        if (reThrowException)
                        {
                            throw
                                new Exception
                                        (
                                            innerExceptionMessage
                                            , e
                                        );
                        }
                    }
                    finally
                    {
                        //Console.WriteLine("Finally");
                        if (onFinallyProcessAction != null)
                        {
                            onFinallyProcessAction(caughtException, exception);
                        }
                    }
                }
                else
                {
                    onTryProcessAction();
                }
            }
        }
    }
}

posted @ 2013-01-06 20:58  于斯人也  阅读(355)  评论(0编辑  收藏  举报