处理应用程序级错误

时间:2012-04-03 11:11:32

标签: asp.net-mvc application-error

我有代码(在Internet上找到)来处理应用程序错误。我在事件日志中写道。

void Application_Error(object sender, EventArgs e)
       {
           Exception myError = null;

           if (HttpContext.Current.Server.GetLastError() != null)
           {
               string eventLog = "MySite";
               string eventSource = "www.mysite.com";
               string myErrorMessage = "";

               myError = Server.GetLastError();

               while (myError.InnerException != null)
               {
                   myErrorMessage += "Message\r\n" +
                      myError.Message.ToString() + "\r\n\r\n";
                   myErrorMessage += "Source\r\n" +
                       myError.Source + "\r\n\r\n";
                   myErrorMessage += "Target site\r\n" +
                       myError.TargetSite.ToString() + "\r\n\r\n";
                   myErrorMessage += "Stack trace\r\n" +
                       myError.StackTrace + "\r\n\r\n";
                   myErrorMessage += "ToString()\r\n\r\n" +
                       myError.ToString();

                   myError = myError.InnerException;
               }

               if (EventLog.SourceExists(eventSource))
               {

                   EventLog myLog = new EventLog(eventLog);
                   myLog.Source = eventSource;


                   myLog.WriteEntry("An error occurred in the Web application "
                     + eventSource + "\r\n\r\n" + myErrorMessage,
                       EventLogEntryType.Error);
               }
           }
        }

这是事件日志中的行:

Type    Date         Time       Source         Event             Category
Error   03.04.2012 16:44:41 www.mysite.com  0   "An error occurred in the Web application www.mysite.com

"
Error   03.04.2012 16:43:31 www.mysite.com  0   "An error occurred in the Web application www.mysite.com

"
Error   03.04.2012 16:42:56 www.mysite.com  0   "An error occurred in the Web application www.mysite.com

"
Error   03.04.2012 16:42:56 www.mysite.com  0   "An error occurred in the Web application www.mysite.com

"
Error   03.04.2012 16:42:54 www.mysite.com  0   "An error occurred in the Web application www.mysite.com

"
Error   03.04.2012 16:37:27 www.mysite.com  0   "An error occurred in the Web application www.mysite.com

正如您所指出的,错误大约每秒发生一次。但有关错误的信息是空的 这段代码有什么问题?
感谢。

1 个答案:

答案 0 :(得分:0)

问题出在这行imo

while (myError.InnerException != null)

只有在存在不良情况时才会写出错误的详细信息,但并不总是如此

你也忘了打电话

Server.ClearError();

在处理结束时(但我想这是一个选择)