Getting all messages from InnerException(s)?

前端 未结 12 688
闹比i
闹比i 2020-12-02 07:13

Is there any way to write a LINQ style \"short hand\" code for walking to all levels of InnerException(s) of Exception thrown? I would prefer to write it in place instead of

12条回答
  •  死守一世寂寞
    2020-12-02 08:01

    You mean something like this?

    public static class Extensions
    {
        public static IEnumerable GetInnerExceptions(this Exception ex)
        {
            if (ex == null)
            {
                throw new ArgumentNullException("ex");
            }
    
            var innerException = ex;
            do
            {
                yield return innerException;
                innerException = innerException.InnerException;
            }
            while (innerException != null);
        }
    }
    

    This way you could LINQ over your entire exceptions hierarchy, like this:

    exception.GetInnerExceptions().Where(e => e.Message == "Oops!");
    

提交回复
热议问题