您似乎正在寻找某种基本级别的应用程序错误处理。为什么不在 Global.asax 文件中添加 Application_Error 方法的定义。这将捕获应用程序中出现的任何未处理的异常(来自控制器、其他库或视图等)
示例如下:将其添加到您的 Global.asax:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
//Do your logging here.
//Redirect to an appropriate error page.
}
如果您想知道要记录什么,您可以在此方法中访问异常对象中的大量信息。我通常编写一个类,将其中的一些信息写入文本文件。这是一个示例(在名为 Log 的类中) - 它不是最全面的方法,我确信可以从异常对象中提取更多信息,但是:
public class Log
{
private StreamWriter _writer;
public void WriteErrorMessage(string errorMessage, string pageUrl, Exception e)
{
_writer = new StreamWriter("LOG_FILE_OUTPUT_PATH_HERE.txt", true);
StringBuilder fullError = new StringBuilder();
fullError.AppendLine("Error log: " + DateTime.Now);
fullError.AppendLine(errorMessage);
fullError.AppendLine("Error raised on: " + pageUrl);
fullError.AppendLine("Associated exception message: " + e.Message + "\n" + e.InnerException);
fullError.AppendLine("Exception class: " + e.GetType().ToString());
fullError.AppendLine("Exception source: " + e.Source.ToString());
fullError.AppendLine("Exception method: " + e.TargetSite.Name.ToString());
fullError.AppendLine();
_writer.WriteLine(fullError);
_writer.Flush();
_writer.Close();
}
}
然后,在您的 Application_Error 方法(我们在上面定义的)中调用:
new Log().WriteErrorMessage("Global error has occurred.", Request.Url.ToString(), exception);