从Exception中提取类和文件名

ant*_*ode 9 c# exception

是否可以从异常对象中提取类名和文件名?

我希望将更好的日志记录集成到我的应用程序中,并且我想要包含异常发生位置的详细信息.

在MVC中,Stacktrace不会返回文件名和类名,而我在哪里查找这些名称时有点迷失.

谢谢

Jef*_*ado 22

您可以StackTrace从异常对象创建对象.它将包括StackFrame异常信息的s.然后,您可以找到文件和方法名称,位置等等(如果可用).当然,这应该是不言而喻的,但只有在编译程序集包含调试符号(我认为可以在MVC中使用)时,所有这些都可用.

catch (Exception ex)
{
    var st = new StackTrace(ex, true); // create the stack trace
    var query = st.GetFrames()         // get the frames
                  .Select(frame => new
                   {                   // get the info
                       FileName = frame.GetFileName(),
                       LineNumber = frame.GetFileLineNumber(),
                       ColumnNumber = frame.GetFileColumnNumber(),
                       Method = frame.GetMethod(),
                       Class = frame.GetMethod().DeclaringType,
                   });
    // log the information obtained from the query
}
Run Code Online (Sandbox Code Playgroud)