How ASP.NET gets line numbers in this error generator

Everyone is familiar with the default error handler for ASP.NET. Yellow fields containing the Source error (5 lines of code where the error occurred) and the Source file (file name and line number):

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 create my own error handler and want to get the same pieces of information, but they are not contained in the exception object. Does anyone know how I can get these items.

+2
source share
1 answer

The line number is not available in the Exception itself, but is available in StackTrace, for example:

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
}
+6
source

Source: https://habr.com/ru/post/1533422/


All Articles