2.7. Detecting Errors

Not to sound pessimistic, but just when you think everything is going great, inevitably something goes wrong. The EndRequestEventArgs includes an error property to allow you to detect and react to errors that have occurred during asynchronous requests. The default behavior is to display an error, but you may want to change this to save some user state and navigate to your own error page or to provide a recovery path unique to your application.

To demonstrate, the following code example in Listing 2-26 simply throws a NotImplementedException for postbacks to the server:

Example 2-26. Throwing an exception
<script runat="server">
    protected override void OnLoad(EventArgs e) {
        if(IsPostBack) {
            throw new NotImplementedException("Something terrible has happened!");
        }
    }
</script>

The endRequest() handler then displays the error description and sets the errorHandled property so the PageRequestManager will not react to it any further:

function endRequest(sender, endRequestEventArgs) {
    var theError = endRequestEventArgs.get_error();
    if(theError !== null) {
        alert(theError.description);
        endRequestEventArgs.set_errorHandled(true);
    }
}

The EndRequestEventHandler also exposes a property to indicate whether the request was aborted while it was being processed:

function endRequest(sender, endRequestEventArgs) {
    if(endRequestEventArgs.get_aborted()) {
        alert("Request was aborted");
    }
}

Get Professional ASP.NET 3.5 AJAX now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.