Welcome!

Blog Feed Post

Use jQuery to catch and display ASP.NET AJAX service errors

Another user fed up with your lack of error handling!

If you don’t properly handle the inevitable errors in your web applications, you can expect your users to eventually react about like this guy. Since they typically squelch any server-side errors, AJAX service calls are especially problematic. In fact, they rarely even throw a client-side error when they fail.

Even when a client-side error is thrown, most users won’t notice it and the ones who do notice won’t know what the error means or what to do next. In fact, I’ve found that even many developers don’t notice client-side scripting errors that occur while they’re debugging their own applications!

To help you remedy this problem in your own applications, I want to show you one way that I handle AJAX service call errors with jQuery. To do this, we will build an error-prone web service, make an AJAX request to it via jQuery, handle the resulting server-side errors gracefully, and use a jQuery plugin to attractively present those errors.

Building an erroneous method

To experiment with error handling, the first thing we’ll need is an error. We could use throw() to raise a synthetic error, but let’s build a page method that’s apt to throw a couple of real errors:

[WebMethod]
public static int DivideByZero(int Dividend)
{
  // To fool the compiler into not saving us from ourselves.
  int zero = 0;
 
  return (Dividend / zero);
}

If this method is called with a parameter that cannot be parsed as an integer, it will throw a type conversion error. If we do correctly call it with a string that can be converted to an integer, we’ll get a division by zero exception.

Using jQuery to call the page method

To interface with the page method, we’ll need an input field to supply the dividend and a button to trigger a call to the page method. Something like this:

<html>
<head>
  <title>Division by Zero Utility v1.0</title>
  <script type="text/javascript" src="jquery-1.3.2.min.js"></script>
  <script type="text/javascript" src="default.js"></script>
</head>
<body>
  <input type="text" id="Dividend" />
  <input type="button" id="Divide" value="Divide by 0" />
</body>
</html>

Using jQuery to call an ASP.NET AJAX page method is easy once you understand the required syntax and a few quirks. In default.js, we can use jQuery’s click() to wire our DivideByZero method up to the input button’s click event:

/// <reference path="~/jquery-1.3.2-vsdoc.js />
// When the page loads...
$(document).ready(function() {
  // ...attach an onclick handler to the Divide button.
  $("#Divide").click(function() {
    // Trigger a request to the page method.
    $.ajax({
      type: "POST",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      url: "Default.aspx/DivideByZero",
      // Supply the Dividend value from our input field.
      data: "{ 'Dividend': '" + $("#Dividend").val() + "' }",
      // Error!
      error: function(xhr, status, error) {
        // Display a generic error for now.
        alert("AJAX Error!");
      }
    });
  });
});

Notice the error callback function. This function will be raised in the event of any error or timeout when calling the service. For now, we’ll just display an alert() with a static error message.

If you were to run this example now, typing anything in the input field and hitting the “Divide by 0” button will result in the error handler being called. That’s better than nothing, but wouldn’t it be more useful to display specific information about the exception that occurred?

Inspecting the server’s response in Firebug

To improve the detail of our message, we need to dissect the error returned by the server and find where the specific detail lies. To accomplish this most effectively, I recommend using the Firebug addon to Firefox.

Using Firebug to set a breakpoint on the error handler, we’re able to inspect the request’s state at that point and quickly drill down to the information we’re after:

Inspecting the error's state, using a breakpoint in Firebug

While the status of “error” may seem unhelpful, it is a useful bit of information in some cases. In a more sophisticated error handling scenario, it would allow us to distinguish between a server-side error and a timeout.

However, the undefined error parameter certainly is not helpful.

To find the detail that we need, we’ll have to explore a bit further. Our request’s XMLHttpRequest instance should contain what we’re looking for. Clicking on the green XMLHttpRequest text will shift the Firebug window to inspect that specific object in detail:

Inspecting the XMLHttpRequest object in Firebug

Now we’re getting there: The XMLHttpRequest’s responseText property contains a JSON object with all the detail that the server returned.

As you can see in the Firebug screenshot, the Message variable contains a more familiar .NET error. In this case, indicating that the empty string I submitted was unsuitable for conversion to the Int32 parameter that DivideByZero expects.

Making effective use of the error data

As a string, this JSON object isn’t quite what we need. The last thing we should do is try to parse the error message ourselves. While technically possible, it would be messy and prone to breakage, or require using an extra library such as json2.js.

One of the nice things about JSON is that it is a native JavaScript construct. Thus, JavaScript’s eval() will evaluate a JSON string and return an actual JSON object.

To take advantage of that, we can modify the error handler like this:

error: function(xhr, status, error) {
  // Boil the ASP.NET AJAX error down to JSON.
  var err = eval("(" + xhr.responseText + ")");
 
  // Display the specific error raised by the server (e.g. not a
  //   valid value for Int32, or attempted to divide by zero).
  alert(err.Message);
}

Now, the properties of the error that we got a glimpse of in Firebug are available via the same dot-notation that you’d expect from any object. In particular, the errors returned by ASP.NET AJAX provide three variables in their JSON response: ExceptionType, Message, and StackTrace.

Note: I would normally recommend against using eval() to evaluate a JSON string. However, it is relatively safe in this case since these messages come directly from the .NET framework and do not contain any user-injected content.

Presenting the error message with jQuery

I’ve written about Mike Alsup’s BlockUI plugin before, showing you how to use it to display modal progress indication and confirmation windows. An often overlooked feature of the plugin is the ability to display basic “growl” style notifications.

See the demo at the bottom of this page for an example of that.

After adding a script reference to blockUI.js, displaying the error “growl” couldn’t be easier:

error: function(xhr, status, error) {
  var err = eval("(" + xhr.responseText + ")");
 
  // Display the error "growl", with a title of "Error",
  //  the error message as content, and a 20s display time.
  $.growlUI('Error', err.Message, 20000);
},
success: function() {
  // On the outside chance that our method manages to succeed, 
  //  clear any lingering error "growls".
  $.unblockUI();
}

Since it’s important that the user notice the error message, we can specify a much longer than default timeout for the “growl”. Twenty seconds in the example above.

The success handler is added to make sure any leftover error is cleared after a successful request completes. This avoids any confusion that would be caused by an error message remaining even after a successful request completes.

Because $.growlUI() is just a shortcut for a complex BlockUI usage, $.unblockUI() works on “growl” messages just as if they were $.blockUI() modals.

Note: As with the rest of BlockUI, these “growl” messages can be customized via CSS. For this simple demo, I’m happy with the default styling, but you can easily change it to match your application.

Conclusion

You should never assume your service calls are 100% reliable. This seems obvious, but I’ve encountered mountains of production code without error handling.

As you’ve hopefully seen in this post, it is trivially easy to add great looking error handling to your jQuery service calls. After all is said and done, you’re only looking at about 3-5 extra lines of code. This substantial improvement in usability is well worth the minimal effort.

We focused on an example of using a page method here, but keep in mind that this technique can be implemented to work with both page methods and web service calls.

Source

Download source: jquery-error-handling.zip

###

Originally posted at Encosia. If you're reading this elsewhere, come on over and see the original.

Use jQuery to catch and display ASP.NET AJAX service errors

Read the original blog entry...

More Stories By Dave Ward

Dave Ward wrote his first computer program in 1981, using good ‘ol Microsoft Color BASIC and cassette tapes for data storage. Over the years since then, he has had the opportunity to work on projects ranging from simple DOS applications to global telecommunications networks spanning multiple platforms.

Latest Stories
"The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution and join Akvelon expert and IoT industry leader, Sergey Grebnov, in his session at @ThingsExpo, for an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, will examine the regulations and provide insight on how it affects technology, challenges the established rules and will usher in new levels of diligence...
SYS-CON Events announced today that Calligo has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Calligo is an innovative cloud service provider offering mid-sized companies the highest levels of data privacy. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalized support service from its globally located cloud platfor...
SYS-CON Events announced today that Calligo, an innovative cloud service provider offering mid-sized companies the highest levels of data privacy and security, has been named "Bronze Sponsor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalised support service from its globally located cloud plat...
What sort of WebRTC based applications can we expect to see over the next year and beyond? One way to predict development trends is to see what sorts of applications startups are building. In his session at @ThingsExpo, Arin Sime, founder of WebRTC.ventures, discussed the current and likely future trends in WebRTC application development based on real requests for custom applications from real customers, as well as other public sources of information.
FinTechs use the cloud to operate at the speed and scale of digital financial activity, but are often hindered by the complexity of managing security and compliance in the cloud. In his session at 20th Cloud Expo, Sesh Murthy, co-founder and CTO of Cloud Raxak, showed how proactive and automated cloud security enables FinTechs to leverage the cloud to achieve their business goals. Through business-driven cloud security, FinTechs can speed time-to-market, diminish risk and costs, maintain continu...
SYS-CON Events announced today that SkyScale will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. SkyScale is a world-class provider of cloud-based, ultra-fast multi-GPU hardware platforms for lease to customers desiring the fastest performance available as a service anywhere in the world. SkyScale builds, configures, and manages dedicated systems strategically located in maximum-securit...
21st International Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Me...
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
"With Digital Experience Monitoring what used to be a simple visit to a web page has exploded into app on phones, data from social media feeds, competitive benchmarking - these are all components that are only available because of some type of digital asset," explained Leo Vasiliou, Director of Web Performance Engineering at Catchpoint Systems, in this SYS-CON.tv interview at DevOps Summit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"Outscale was founded in 2010, is based in France, is a strategic partner to Dassault Systémes and has done quite a bit of work with divisions of Dassault," explained Jackie Funk, Digital Marketing exec at Outscale, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We were founded in 2003 and the way we were founded was about good backup and good disaster recovery for our clients, and for the last 20 years we've been pretty consistent with that," noted Marc Malafronte, Territory Manager at StorageCraft, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"DivvyCloud as a company set out to help customers automate solutions to the most common cloud problems," noted Jeremy Snyder, VP of Business Development at DivvyCloud, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.