2

每个人都熟悉 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 

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

4

1 回答 1

6

行号在 Exception 本身中不可用,但在 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
}
于 2013-01-29T15:17:41.053 回答