How does ASP.NET get line numbers in it's generic error handler

拈花ヽ惹草 提交于 2019-12-11 03:51:14

问题


Everyone is familiar with the default error handler for ASP.NET. The yellow boxes that contain Source Error (5 lines of code where the error happened) and Source File (filename and line number) like so:

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 

I am building a custom error handler and want to get these same pieces of information, but they are not contained in the exception object. Does anyone know how I may retrieve these items.


回答1:


The line number is not available in the Exception itself, but it is available in the StackTrace, like so:

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
}


来源:https://stackoverflow.com/questions/14586107/how-does-asp-net-get-line-numbers-in-its-generic-error-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!