Friday, January 30, 2009

C#: Generic Error Handling Routine (WinApp)

Just call the LogError method from any function within the catch block and pass the exception (ex) to this method...

public static void LogError(Exception ex)
{
string EventLogSourceName = "Application Name";
int EventLogErrorCode = "99";
string msg = "The application encountered an unknown error:";
msg += "\r\nExecuting Method: " + new System.Diagnostics.StackFrame(1, false).GetMethod().Name;
msg += "\r\nError Message: " + ex.Message;

EventLog.WriteEntry(EventLogSourceName, msg, EventLogEntryType.Error, EventLogErrorCode);
MessageBox.Show(msg, "ERROR", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
}