问题描述
发生错误时,我想获取方法名称和行号,我正在使用Core 5。
try
{
//My code
}
catch (Exception ex)
{
_logger.LogError(ex,"Method Name / Line Number");
}
更新:
我找到了这样的解决方案:
_logger.LogError(ex,"\n=> ex Error: " + ex + "\n=> Action Name: " + ex.TargetSite.ReflectedType.Name + "\n=> Error Message: " + ex.Message + "\n=> Line Number: " + ex.LineNumber());
解决方法
在异常情况下简单调用ToString()
即可为您提供所需的完整信息。例如,当我们运行以下代码时:
public static void Main()
{
try
{
//my code
throw new ArgumentException();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
输出将类似于:
System.ArgumentException: Value does not fall within the expected range.
at ConsoleApp.Program.Main() in C:\Users\USER\source\Playground\ConsoleApp1\Program.cs:line 20
其中Main()
是方法名称,而 20 是行号。
要获取有问题的格式,我们可以为异常编写包装,并从异常中获取行号:
using System;
using System.Reflection;
namespace ConsoleApp
{
class Program
{
public static void Main()
{
try
{
//my code
throw new ArgumentException();
}
catch (Exception ex)
{
Console.WriteLine(MethodBase.GetCurrentMethod().Name + "/" + GetLineNumber(ex));
}
}
public static int GetLineNumber(Exception ex)
{
var lineNumber = 0;
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
if (int.TryParse(lineNumberText,out lineNumber))
{
}
}
return lineNumber;
}
}
}
注意:在提取行方法中,我们正在获取最常见的异常。当我们在堆栈跟踪中有一连串异常时,这很方便。