赞
踩
不知你有没有留意过ASP.net的异常,如下图:
请留意图中用红笔标的地方。那些数字标明出错处位于源代码文件的多少行。
但是,我们通过 Exception.StackTrace 是获得不了这个信息的。这个信息是如何获得呢?这就要用到下面两个类:
System.Diagnostics.StackTrace | 表示一个堆栈跟踪,它是一个或多个堆栈帧的有序集合。 |
System.Diagnostics.StackFrame | 表示当前线程的调用堆栈中的一个函数调用 |
下面的代码就替我们扑捉了更多关于异常的信息:
public static string EnhancedStackTrace(Exception ex)
{
return EnhancedStackTrace(new StackTrace(ex, true));
}
public static string EnhancedStackTrace(StackTrace st)
{
StringBuilder sb = new StringBuilder();
sb.Append(Environment.NewLine);
sb.Append("---- Stack Trace ----");
sb.Append(Environment.NewLine);
for (int i = 0; i < st.FrameCount; i++)
{
StackFrame sf = st.GetFrame(i);
MemberInfo mi = sf.GetMethod();
sb.Append(StackFrameToString(sf));
}
sb.Append(Environment.NewLine);
return sb.ToString();
}
public static string StackFrameToString(StackFrame sf)
{
StringBuilder sb = new StringBuilder();
int intParam;
MemberInfo mi = sf.GetMethod();
sb.Append(" ");
sb.Append(mi.DeclaringType.Namespace);
sb.Append(".");
sb.Append(mi.DeclaringType.Name);
sb.Append(".");
sb.Append(mi.Name);
// -- build method params
sb.Append("(");
intParam = 0;
foreach (ParameterInfo param in sf.GetMethod().GetParameters())
{
intParam += 1;
sb.Append(param.Name);
sb.Append(" As ");
sb.Append(param.ParameterType.Name);
}
sb.Append(")");
sb.Append(Environment.NewLine);
// -- if source code is available, append location info
sb.Append(" ");
if (string.IsNullOrEmpty(sf.GetFileName()))
{
sb.Append("(unknown file)");
//-- native code offset is always available
sb.Append(": N ");
sb.Append(String.Format("{0:#00000}", sf.GetNativeOffset()));
}
else
{
sb.Append(System.IO.Path.GetFileName(sf.GetFileName()));
sb.Append(": line ");
sb.Append(String.Format("{0:#0000}", sf.GetFileLineNumber()));
sb.Append(", col ");
sb.Append(String.Format("{0:#00}", sf.GetFileColumnNumber()));
if (sf.GetILOffset() != StackFrame.OFFSET_UNKNOWN)
{
sb.Append(", IL ");
sb.Append(String.Format("{0:#0000}", sf.GetILOffset()));
}
}
sb.Append(Environment.NewLine);
return sb.ToString();
}
一个扑捉的信息如下:
---- Stack Trace ----
WebErrorTestProject.WebForm1.Page_Load(sender As Objecte As EventArgs)
WebForm_GetError.aspx.cs: line 0018, col 13, IL 0016
System.Web.Util.CalliHelper.EventArgFunctionCaller(fp As IntPtro As Objectt As Objecte As EventArgs)
(unknown file): N 00015
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(sender As Objecte As EventArgs)
(unknown file): N 00033
System.Web.UI.Control.OnLoad(e As EventArgs)
(unknown file): N 00099
System.Web.UI.Control.LoadRecursive()
(unknown file): N 00047
System.Web.UI.Page.ProcessRequestMain(includeStagesBeforeAsyncPoint As BooleanincludeStagesAfterAsyncPoint As Boolean)
(unknown file): N 01436
通过这些错误信息,可以帮助我们更容易的解决问题。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。