Getting all messages from InnerException(s)?

前端 未结 12 715
闹比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:07

    I don't think so, exception is not an IEnumerable so you can't perform a linq query against one on its own.

    An extension method to return the inner exceptions would work like this

    public static class ExceptionExtensions
    {
        public static IEnumerable InnerExceptions(this Exception exception)
        {
            Exception ex = exception;
    
            while (ex != null)
            {
                yield return ex;
                ex = ex.InnerException;
            }
        }
    }
    

    you could then append all the messages using a linq query like this:

    var allMessageText = string.Concat(exception.InnerExceptions().Select(e => e.Message + ","));
    

提交回复
热议问题