C#错误和异常之调用者信息

2019-02-25  本文已影响3人  当我写下一亿行代码

在处理错误时,希望能够获取到错误发生的位置信息。通过特性CallerLineNumber、CallerFilePath、CallerMemberName分别获知调用者的行数、文件路径以及调用成员。

新建一个CallerInformationHelper类:

using System;
using System.Runtime.CompilerServices;

namespace CallerInfomation
{
    public class CallerInformationHelper
    {
        public void Log([CallerLineNumber] int line = -1,
            [CallerFilePath] string path = null,
            [CallerMemberName] string name = null)
        {
            Console.WriteLine((line < 0) ? "No line" : "Line" + line);
            Console.WriteLine((path == null) ? "No file path" : path);
            Console.WriteLine((name == null) ? "No member name" : name);

            Console.WriteLine();
        }

        private int someProperty;
        public int SomeProperty
        {
            get { return someProperty; }
            set
            {
                this.Log();
                someProperty = value;
            }
        }
        
    }
}

编写一些测试代码:

using System;

namespace CallerInfomation
{
    class Program
    {
        static void Main(string[] args)
        {
            CallerInformationHelper helper = new CallerInformationHelper();
            helper.Log();
            helper.SomeProperty = 33;

            Action a1 = () => helper.Log();
            a1();
            
            Console.ReadLine();
        }        
    }
}

最后在控制台的输出如下:

Line10
E:\dotnet\Chapter16\CallerInfomation\Program.cs
Main

Line25
E:\dotnet\Chapter16\CallerInfomation\CallerInformationHelper.cs
SomeProperty

Line13
E:\dotnet\Chapter16\CallerInfomation\Program.cs
Main

不禁要思考一个问题,调用者信息如何使用到实际的代码中,以确定异常发生在哪一行。目前调试阶段是通过try-catch与pdb文件,编写形如以下代码的方式查看异常发生的信息:

try
{
    ...
}
catch(Exception ex)
{
    //自定义一个日志记录方法
    LogRecord.Log(Class.Name,ex.ToString());
}
···

上一篇下一篇

猜你喜欢

热点阅读