Handling errors in asp.net Ajax
The default configuration for asp.net Ajax simply shows an alert box if your asynchronous postback causes an exception. This may not be the appropriate way you want to handle exceptions in your application. Here is a simple markup that illustrates this behavior.
In the above code I have a button inside of an Update Panel. The button click event throws an exception. Since I have not told asp.net Ajax how to handle exceptions you get an ugly alert box showing the exception that has occurred. To resolve this issue, you decide we like to handle our exceptions globally and show a friendly error message page to the user. In order to register a global exception handler, we can set a default redirect page when an exception occurs in our application inside our web.config file. Here is the setting that I can specify in my web.config file.
The above line is all you need to tell script manager to redirect the user to a friendly error page called CustomError.aspx when an exception occurs in the application. After applying the setting above in the web.config, when you click on the button that causes an exception you get a friendly error page as shown below.
The option discussed above is a good way to solve exceptions in a generic way. However there are times when you want to handle exceptions on certain page differently. In that case you would want to override the default behavior of custom error defined in web.config file. To handle error differently on a certain page, you need to set AllowCustomErrorsRedirect to false on script manager. Handle onasyncpostbackerror event on script manager to customize the error message that is sent to the client. Once the error has been customized you need handle the error on the client side so user can see that friendly error message. To accomplish this you register with the endrequest event of pagerequest manager. endRequest is an event that gets raised by pagerequest manager when the response has arrived from the server. The event will get raised regardless if an exception occurred on the server. One of arguments that is sent to the endrequest event is the error message sent by the server. Inside the event you the opportunity to display that error message to the user. Here is an example that illustrates it fully.
In the above code I have allowcustomredirects set to false on scriptmanager. I am also registering for onasyncpostback error event handler. On my registered event, I am simply appending extra text in addition to the error that I received as an argument to the method. On the client side, I simply get the error message from the argument and assign the message to the inner html of error div. I also need to set error handled to true to tell scriptmanager that I have handled the error.