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
DX World EXPO, LLC, a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of the 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to gre...
DevOps is under attack because developers don’t want to mess with infrastructure. They will happily own their code into production, but want to use platforms instead of raw automation. That’s changing the landscape that we understand as DevOps with both architecture concepts (CloudNative) and process redefinition (SRE). Rob Hirschfeld’s recent work in Kubernetes operations has led to the conclusion that containers and related platforms have changed the way we should be thinking about DevOps and...
The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, demonstrated how to move beyond today's coding paradigm and shared the must-have mindsets for removing complexity from the develop...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
The next XaaS is CICDaaS. Why? Because CICD saves developers a huge amount of time. CD is an especially great option for projects that require multiple and frequent contributions to be integrated. But… securing CICD best practices is an emerging, essential, yet little understood practice for DevOps teams and their Cloud Service Providers. The only way to get CICD to work in a highly secure environment takes collaboration, patience and persistence. Building CICD in the cloud requires rigorous ar...
Companies are harnessing data in ways we once associated with science fiction. Analysts have access to a plethora of visualization and reporting tools, but considering the vast amount of data businesses collect and limitations of CPUs, end users are forced to design their structures and systems with limitations. Until now. As the cloud toolkit to analyze data has evolved, GPUs have stepped in to massively parallel SQL, visualization and machine learning.
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
"ZeroStack is a startup in Silicon Valley. We're solving a very interesting problem around bringing public cloud convenience with private cloud control for enterprises and mid-size companies," explained Kamesh Pemmaraju, VP of Product Management at ZeroStack, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Enterprises are adopting Kubernetes to accelerate the development and the delivery of cloud-native applications. However, sharing a Kubernetes cluster between members of the same team can be challenging. And, sharing clusters across multiple teams is even harder. Kubernetes offers several constructs to help implement segmentation and isolation. However, these primitives can be complex to understand and apply. As a result, it’s becoming common for enterprises to end up with several clusters. Thi...