C#程序在某个方法执行出错,打印当前执行方法名称,便于排查错误!

using System;
using System.Diagnostics;
using ConsoleExtClass;

namespace WhenErrorPrintExecuteMethod
{
    /// <summary>
    ///     https://www.cnblogs.com/LifeDecidesHappiness/p/15638935.html
    ///     C#程序在某个方法执行出错,打印当前执行方法名称,便于排查错误!
    ///     LDH @ 2021-12-3
    /// </summary>
    internal class Program
    {
        private static void Main()
        {
            Console.Title = "C#程序在某个方法执行出错,打印当前执行方法名称,便于排查错误!";

            WhenDivideByZeroExceptionOccurs();

            Console.ReadKey();
        }

        /// <summary>
        ///     当程序执行有错误时候,抛出异常,并打印出所在方法名称,便于排查
        /// </summary>
        private static void WhenDivideByZeroExceptionOccurs()
        {
            // 获取执行方法名称
            var method = new StackTrace().GetFrame(0).GetMethod();

            try
            {
                var a = 5;
                var b = 0;
                var c = a / b;
                Console.WriteLine("Result:" + c);
            }
            catch (Exception ex)
            {
                PrintLine();
                var info = $"出现错误的方法名:{method.Name},{Environment.NewLine}具体错误如下:{Environment.NewLine}{ex.Message}";
                Console.WriteLine(info);

                PrintLine();
                ConsoleExt.ErrorLine(info, true);

                PrintLine();
            }
        }

        private static void PrintLine()
        {
            Console.WriteLine("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
        }
    }
}

 

本文作者:Love In Winter
本文链接:https://www.cnblogs.com/LifeDecidesHappiness/p/15638935.html
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以扫一扫,任意打赏,您的鼓励是博主的最大动力!
扫一扫,支付宝打赏 扫一扫,微信打赏
原文地址:https://www.cnblogs.com/LifeDecidesHappiness/p/15638935.html