Handling AJAX Errors


This article explains about handling different types of AJAX errors in ASP. Net applications. If an error happens due to Ajax call usually it shows up as a Pop-up message through java script to the user. Based upon our requirement we can suppress / modify the error message.

For suppressing an AJAX error through java script add the below line at end of your page

   <script>
   Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, args) { 
        if (args.get_error() && args.get_error().name === 'Sys.WebForms.PageRequestManagerServerErrorException')
             {                          
            args.set_errorHandled(true); 
            }           
    });       

</script>

To handle the error in Asp.Net code add "OnAsyncPostBackError" attribute to script manager and declare an event in the code behind

<asp:ScriptManager ID="ScriptManager1" runat="server" OnAsyncPostBackError="ScrptMgr_AsyncPostBackError" >
</asp:ScriptManager>

protected void ScrptMgr_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)

{
    Response.Redirect("ErrorPage.aspx");
}

But if you decide to show the AJAX error with some meaningfull information, you can assign the error message to AsyncPostBackErrorMessage property of your script manager instance

protected void ScrptMgr_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)

{
    ScriptManager1.AsyncPostBackErrorMessage="Sorry, Error occured while processing"
}

Another error users frequently encounter is AJAX Script timeout error, the timeout can be increased by changing the "AsyncPostBackTimeout" value.

But if you like to suppress the AJAX timeout error add the below code at end of your page...

<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, args) { if (args.get_error() && args.get_error().name === 'Sys.WebForms.PageRequestManagerTimeoutException')
{
    args.set_errorHandled(true);
}
});
</script>


 


Similar Articles