ASP.NET如何在其通用错误处理程序中获取行号

Cod*_*rue 2 asp.net exception-handling

每个人都熟悉ASP.NET的默认错误处理程序.包含源错误的黄色框(发生错误的5行代码)和源文件(文件名和行号)如下所示:

Source Error:

Line 48:         public ActionResult TriggerException()
Line 49:         {
Line 50:            throw new SystemException("This is a generated exception to test the global error handler.");
Line 51:         }
Line 52:         


Source File: c:\MyApp\Controllers\TestToolsController.cs    Line: 50 
Run Code Online (Sandbox Code Playgroud)

我正在构建一个自定义错误处理程序,并希望获得这些相同的信息,但它们不包含在异常对象中.有谁知道我如何检索这些项目.

Roy*_*tus 6

行号本身不提供行号,但它在StackTrace中可用,如下所示:

try
{
    // code that throws an Exception here
}
catch (Exception exc)
{
    var frame = new StackTrace(exc, true).GetFrame(0); // where the error originated
    var lineNumber = frame.GetFileLineNumber();
    // Handle line numbers etc. here
}
Run Code Online (Sandbox Code Playgroud)