interviews.dotnetthread.com

↑ Grab this Headline Animator

Friday, January 16, 2009

Log Unhandled Exceptions in Application and redirect users to Custom Error Page.

To catch the unhandled exceptions in the application we need to handle Application_Error event Handler in Global.asax file.

Add Global.asax file to the project then in Application_Error method we can get the Exception by using Server.GetLastError(). Then we can log the error discription into Log file or Database.


void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception ex = Server.GetLastError().GetBaseException();
string errorMessage = ex.Message.ToString();

// Log the error Here into Log file or Database

}


Now to redirect the user to Custom Error page on un-handled exceptions in web.config under CustomErrors section make Mode="On" and set defaultRedirect to ErrorPage.

We can also have different error pages for different errors as below, for 404 file not found.

<customErrors mode="On"defaultRedirect="ErrorPage.aspx">
<errorstatusCode="403"redirect="NoAccess.htm" />
<errorstatusCode="404"redirect="FileNotFound.htm" />
</customErrors>

Submit this story to DotNetKicks

2 comments:

Arnold Matusz said...

I've also written a blog post about how to do global exception handling and how you would display all the exception details on a custom error page!

http://blog.dreamlabsolutions.com/post/2008/10/01/ASPnet-global-exception-handling-and-custom-error-page.aspx

Sangam Uprety said...

Thanks. Now we could log the error using our favourite logging mechanism. Some may prefer logging the error in text files and others may log them in the database. Whatever be the way, this will help diagnose any error occurred in the production environment. Thanks.

Post a Comment

Post your comments/questions/feedback for this Article.

 

Latest Articles