如何在ASP Core 5中的Exception中获取方法名称和行号



我想在发生错误时获得方法名称和行号,我使用的是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:UsersUSERsourcePlaygroundConsoleApp1Program.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;
}
}
}

注意:在提取行方法中,我们提取最顶端的异常。当我们的堆栈跟踪中有一系列异常时,这就派上了用场。

最新更新