Wednesday, September 23, 2020

Capturing the file name and line number of an Exception

Handling exceptions is a critical task in any application.  When an exception is logged, it needs to have sufficient detail so it can be researched at a later time.  In addition, as a developer, you want to extract and log as much detail about it as possible.  Some of those details include the file name and line number where the exception occurred.  Listed below is a method that handles exceptions, extracts the message, file name, and line number for logging.

 

 

        private void ProcessEx(Exception ex, string details = "")

        {

            int lineNumber = 0;

            const string lineNumberMarker = ":line ";

            string traceText = ex.StackTrace + "";  //Adding empty space will ensure final value is never null

 

            int lineIndex = traceText.LastIndexOf(lineNumberMarker);

            if (lineIndex >= 0)

            {

                string lineNumberText = traceText.Substring(lineIndex + lineNumberMarker.Length);

                int.TryParse(lineNumberText, out lineNumber);

            }

 

            string fileName = string.Empty;

            const string fileNameMarker = " in ";

            int fileNameIndex = traceText.LastIndexOf(fileNameMarker);

            if (fileNameIndex >= 0)

            {

                int fileNameStart = fileNameIndex + fileNameMarker.Length;

                int fileNameLength = lineIndex - fileNameIndex - fileNameMarker.Length;

                fileName = traceText.Substring(fileNameStart, fileNameLength);

            }

 

            //Log error message + file/line info

            string msg = $"Error: {ex.Message}. \r\n{details}";

            string fileInfo = $"\r\nFile {fileName}, Line {lineNumber} ";

            Logging lg = new Logging();

            lg.WriteLog(msg + fileInfo);           

        }

 

No comments:

Post a Comment