星期二, 4月 11, 2023

[C#] AggregateException

AggregateException 代表應用程式執行期間所發生的一或多個錯誤,就直接看範例來理解

範例一:收集連續不中斷流程中的 Exception

AggregateException.ToString() 可以列出全部 Exception
namespace AggregateExceptionSample
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ProcessCollection();
        }

        static void ProcessCollection()
        {
            string number = "1234567890";

            Action<string> a1 = s => throw new Exception(nameof(s));
            Action<string> a2 = s => throw new DivideByZeroException(nameof(s));
            Action<string> a3 = s => throw new NotSupportedException(nameof(s));

            var methods = new List<Action<string>>()
            {
                a1 ,
                a2 ,
                a3
            };

            var exceptions = new List<Exception>();
            foreach (var method in methods)
            {
                try
                {
                    method(number);
                }
                catch (Exception ex)
                {
                    exceptions.Add(ex);
                }
            }

            if (exceptions.Any())
            {
                try
                {
                    throw new AggregateException("發生錯誤", exceptions);
                }
                // 使用 ToString() 列出上述三個 Exception
                catch (AggregateException ex)
                {
                    Console.WriteLine("顯示全部的 Exception 訊息");
                    Console.WriteLine("-------------------------");
                    Console.WriteLine(ex.ToString());
                }
            }
        }
    }
}

[C#] AggregateException-1

範例二:Flatten 方法官方文章範例

該範例在一個 Task 內發動子 Task 來蒐集 Exception,使用 C# 6.0 Exception Filter 來修正原範例 foreach Exception 判斷
namespace AggregateExceptionSample
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Flatten();
        }

        static void Flatten()
        {
            var task1 = Task.Factory.StartNew(() =>
            {
                var child1 = Task.Factory.StartNew(() =>
                {
                    var child2 = Task.Factory.StartNew(() =>
                    {
                        // This exception is nested inside three AggregateExceptions.
                        throw new CustomException("Attached child2 faulted.");
                    }, TaskCreationOptions.AttachedToParent);

                    // This exception is nested inside two AggregateExceptions.
                    throw new CustomException("Attached child1 faulted.");
                }, TaskCreationOptions.AttachedToParent);
            });

            try
            {
                task1.Wait();
            }
            // 使用 C# 6.0 Exception Filter 來篩選 Exception
            catch (AggregateException ae) when
            (
                ae
                .Flatten()
                .InnerExceptions
                .Any(e => e.GetType() == typeof(CustomException))
            )
            {
                Console.WriteLine(ae.Message);
            }
        }
    }

    public class CustomException : Exception
    {
        public CustomException(string message) : base(message)
        {

        }
    }
}
[C#] AggregateException-2

沒有留言:

張貼留言