Getting all messages from InnerException(s)?

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

    I'm just going to leave the most concise version here:

    public static class ExceptionExtensions
    {
        public static string GetMessageWithInner(this Exception ex) =>
            string.Join($";{ Environment.NewLine }caused by: ",
                GetInnerExceptions(ex).Select(e => $"'{ e.Message }'"));
    
        public static IEnumerable GetInnerExceptions(this Exception ex)
        {
            while (ex != null)
            {
                yield return ex;
                ex = ex.InnerException;
            }
        }
    }
    

提交回复
热议问题