In my experience, I have seen developers use variety of techniques for handling exceptions. Some developers surround each and every block of code with a Try...Catch. Some developers let them bubble up and handle them in the Main method for windows applications or handle them at the application level in the Application_Error method of the Global.asax file or handle them at the page level in the Page_Error method of the .aspx file for Web applications.
My take on Exception handling is that all exceptions should be logged no matter where you catch them. You could log them to the event log, database or file.
There are three general cases when Try...Catch blocks make sense:
1. When there is an opportunity to recover from the application by taking some alternative course of action. For Example: If an SMTP server fails, you may want to connect to a back up SMTP server.
2. When an exception indicates a problem that should not impede the current flow, log the exception and swallow the exception. For Example: If an email notification fails after an order is processed, you may just want to log the error and proceed.
3. When additional information needs to be included with the exception. In this case it is useful to catch the exception and re throw a new exception with the original exception as an inner exception.
There are Error Logging and notification libraries you could use like ELMAH.
Below is the example code on how to handle errors in Application_Error event of Global.asax file:
protected void Application_Error(object sender, EventArgs e)
{
HttpContext ctx = HttpContext.Current;
if (ctx == null) return;
Exception exception = ctx.Server.GetLastError();
if (exception.InnerException != null)
{
EventLog MyLog = new EventLog();
MyLog.Source = e.Source;
MyLog.WriteEntry(e.Message + " " + e.StackTrace);
Response.Redirect("error.html");
}
}
No comments:
Post a Comment