(精华)2020年6月26日 C#类库 异常处理帮助类

using System;
using System.Linq;
using System.Text;

namespace Core.Util
{
    /// 
    /// 异常处理帮助类
    /// 
    public static class ExceptionHelper
    {
        /// 
        /// 获取异常位置
        /// 
        /// 异常
        /// 
        private static string GetExceptionAddr(Exception e)
        {
            StringBuilder excAddrBuilder = new StringBuilder();
            e?.StackTrace?.Split("\r\n".ToArray())?.ToList()?.ForEach(item =>
            {
                if (item.Contains("行号") || item.Contains("line"))
                    excAddrBuilder.Append($"    {item}\r\n");
            });

            string addr = excAddrBuilder.ToString();

            return addr.IsNullOrEmpty() ? "    无" : addr;
        }

        /// 
        /// 获取异常消息
        /// 
        /// 捕捉的异常
        /// 内部异常层级
        /// 
        private static string GetExceptionAllMsg(Exception ex, int level)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append($@"{level}层错误:消息:{ex?.Message}位置:{GetExceptionAddr(ex)}");
            if (ex.InnerException != null)
            {
                builder.Append(GetExceptionAllMsg(ex.InnerException, level + 1));
            }

            return builder.ToString();
        }

        /// 
        /// 获取异常消息
        /// 
        /// 捕捉的异常
        /// 
        public static string GetExceptionAllMsg(Exception ex)
        {
            string msg = GetExceptionAllMsg(ex, 1);
            return msg;
        }
    }
}

你可能感兴趣的:(#,C#类库/扩展方法)