Wednesday, November 19, 2008

Asp.net Application Level Error Handling from Global.asax global page

There may be tens, if not hundreds, of loop holes in an asp.net web application. It cannot be predicted which line in an .aspx.cs code behind file leads to unknown error. So to fetch the error occurred and inform the user in a friendly way, we can use the Application_Error event handler of global.asax file in asp.net web application.

Just add the global.asax file in the root of your asp.net web application. Now customize the following Application level error handler:

void Application_Error(object sender, EventArgs e)

{

Server.Transfer("~/Errors/CustomErrorPage.aspx?error=" + Server.GetLastError().Message);

}

This code will fetch the last error and redirects to the page CustomErrorPage.aspx create in Errors folder. Remember that the error message has been passed in the QueryString 'error'. The CustomErrorPage.aspx page will fetch the error from the Request Parameter and display it in the asp.net label control in its Page_Load event.

protected void Page_Load(object sender, EventArgs e)

{


if (!IsPostBack)

{

lblError.Text = Request.QueryString["error"].ToString();

}

}

This way you are done.

Of course, I have been blogging about custom error handling in asp.net web page from web.config file, in one of my earlier post. In that post, I devised the way to redirect to user friendly error pages when particular error occurred. I added that it was the presentation layer error handling practice. You can check the best practice of error handling in sql server 2005 stored procedure. And it was the error handling practice in the database level. We may handle erro, no doubt, but I always prefer the user friendly error handling in asp.net web page in presentation layer. The trick I am discussing in this post is all about handling error in the application level. Any errors unhandled otherwise will be caught and the user will be prompted with the error detail.

Your comment and suggestion are very valuable for this blog. You can comment this article. Further you can share this article by social-bookmarking it. Don't forget to subscribe the posts that are posted in this blog. You will get them all in your e-mail inbox! Happy programming!!

0 comments:

Post a Comment

Hope you liked this post. You can leave your message or you can put your valuable suggestions on this post here. Thanks for the sharing and cooperation!

Popular Posts

Recent Articles