.NET Core表达式树中添加调试信息至异常堆栈跟踪的方法
在.NET Core表达式树中添加调试信息至异常堆栈跟踪
可以在.NET Core的表达式树中插入调试信息,让自定义的源代码位置(如test.txt)和函数名显示在异常堆栈跟踪里,但需要调整编译方式并正确配置调试节点。
关键调整点
使用带调试符号生成器的编译重载
默认的Compile()方法不会生成调试符号,必须使用Compile(DebugInfoGenerator)重载,指定DebugInfoGenerator.CreatePdbGenerator()(.NET Core 3.0及以上版本支持)来启用动态调试符号生成。自定义lambda函数名(可选)
通过Expression.Lambda的重载指定方法名,替换默认的lambda_methodN命名,让堆栈跟踪更易读。
修改后的示例代码
// Define the lambda expression var x = Expression.Parameter(typeof(int), "x"); var y = Expression.Parameter(typeof(int), "y"); var op = Expression.Divide(x, y); var debug = Expression.DebugInfo( Expression.SymbolDocument("test.txt"), 1, 5, 4, 13); var bl = Expression.Block(debug, op); // 指定自定义函数名,并使用调试符号生成器编译 var lambdaExpr = Expression.Lambda<Func<int, int, int>>( bl, "DivideNumbers", // 自定义函数名 new[] { x, y }); // 使用DebugInfoGenerator生成调试符号 var compiled = lambdaExpr.Compile(DebugInfoGenerator.CreatePdbGenerator()); // Create a function that invokes the compiled delegate with some arguments Func<int, int, int> invokeDelegate = (xArg, yArg) => compiled(xArg, yArg); // Invoke the function with some arguments invokeDelegate(20, 0);
预期的异常堆栈跟踪
修改后,抛出的DivideByZeroException堆栈跟踪会包含自定义的源文件和函数名:
Unhandled exception. System.DivideByZeroException: Attempted to divide by zero. at DivideNumbers(Int32 , Int32 ) in test.txt:line 1 at ExpressionTreeExample.<>c__DisplayClass0_0.<Main>b__0(Int32 xArg, Int32 yArg) in .../workspace/test/Program.cs:line 23 at ExpressionTreeExample.Main() in .../workspace/test/Program.cs:line 26
注意事项
- .NET Core版本要求:
DebugInfoGenerator.CreatePdbGenerator()仅在.NET Core 3.0及以上可用,更早版本无法通过这种方式生成动态调试符号。 - 调试信息节点的位置:
Expression.DebugInfo的行号、列号参数需要对应你想标记的代码位置,确保异常发生时能关联到正确的自定义源信息。
内容的提问来源于stack exchange,提问作者Pero P
相关产品推荐
相关产品推荐

