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


using System;
using System.Diagnostics;
using ConsoleExtClass;

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

            WhenDivideByZeroExceptionOccurs();

            Console.ReadKey();
        }

        /// 
        ///     当程序执行有错误时候,抛出异常,并打印出所在方法名称,便于排查
        /// 
        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("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
        }
    }
}