WCF and jQuery Exception Handling

Now that I have covered the basics of calling a WCF service using jQuery’s AJAX functionality with JSON its time to deal with bugs. Yep, we all create them and have to troubleshoot them on a daily basis. Even if you are not actually coding the WCF service you need to know how to deal with any exception that may be bubbled back to the client when you call a service API method.

If you remember there were a few items I referenced in the previous post on the jQuery side of this transaction to deal with errors. The first is a DIV element to hold any error messages you may want to display to the user called AJAXError. In the jQuery Ready method I told this element to response to the global ajaxError event handler by displaying some diagnostic information to the user.

$(

"#AJAXError"

).ajaxError(

function

(

event

, request, settings) {
$(

this

).append(

"Error requesting page "

+
(settings.url) ? settings.url :

''

+

"<br/>http Status Code: "

+
(request.status) ? request.status :

''

+

"<br/>http Status:"

+
(request.statusText) ? request.statusText :

''

);
});

Now in production I do not recommend displaying a message like this to the end user. I will discuss ways to handle this more gracefully later.

AJAX Error handling

The next item included in the sample code is a generic OnPageError method that is executed in the .ajax error callback method. You can either call this directly or inside a more custom error handler. I want to point out there are three parameters it processes, one for the XMLHttpRequest object, the is a string that describes the error and finally an exception object if any.

The following code snippet shows a basic error processing event handler. The showErrorMsg method in this example is designed to display an appropriate message to the user. But in reality the OnPageError method should be much more complex to process all sorts of scenarios

function

OnPageError(xhr, errorMsg, thrown) {

if

(

typeof

xhr ==

"string"

) {
showErrorMsg(xhr);

return

;
}

else

if

(

typeof

(xhr.responseText) ==

"string"

&& xhr.responseText !=

""

)
{
showErrorMsg(xhr.responseText);
}

else

{
showErrorMsg(

"Unknown error occurred in callback."

);
}
}

An example of a custom error callback that eventually calls the OnPageError method is below, it closes the processing message to make the page available again. You may need to clean up some things depending on your needs like the example below. This is why I like creating a custom callback method instead of passing the OnPageError method directly. Click the image below to see the detail of the XMLHttpRequest object when a typical exception is thrown.

XMLHttpRequest Error handling

One thing you need to realize is JavaScript is very flexible and when an error is thrown in the AJAX process you may not get all these parameters, it might just be the errorMsg parameter or the thrown (exception object) parameter. This is why you need to build out an even more robust routine to process the parameters. A more robust method would process an exception object. If an exception is bubbled up through the WCF service it will be serialized, in our example it will be a JSON object. This means we can parse the exception object and handle it more gracefully.

function

OnPageError(xhr, errorMsg, thrown) {

if

(

typeof

xhr ==

"string"

) {
showErrorMsg(xhr);

return

;
}

else

if

(

typeof

(xhr.responseText) ==

"string"

&& xhr.responseText !=

""

) {

var

err = JSON2.parse(xhr.responseText);

switch

(err.ExceptionType) {

case

'System.Exception'

:
showErrorMsg(err.Message);

return

;

default

:
showErrorMsg(xhr.responseText);

return

;
}
}

else

{
showErrorMsg(

"Unknown error occurred in callback."

);
}

}

Since it is a JSON object you can simply use the JSON2.parse method to hydrate the object and then process it as if it were on the in the .NET code you are use to working with.

error: 

function

(xhr, errorMsg, thrown) {
$.unblockUI();
OnPageError(xhr, errorMsg, thrown);
}

Great now you can gracefully handle exceptions for the user, what should you do now to figure out the bug and squash it? First realize an exception could be thrown in one of two places; the client or the server (inside the web service). The first order of business is to determine what side of the request the issue resides.

The first place to look is the Http Status code sent from the server. If you have a 500 value it was the server. If you don’t have a value or it is 200 or another non 500 series value the odds are it is in the client code. I make a lot of typos when I am typing from scratch, so those have gotten me quite a bit in my learning process. Often it was simply an improper case since JavaScript is very strict when it comes to casing. So knowing if it is in the service or the JavaScript is real important to solve the issue.

I primarily work in Internet Explorer, so the first place I tend to look is the development tools and take advantage of the fantastic debugging facilities built into the browser. I reviewed these techniques in a previous post. If you are working in FireFox Firebug is your friend. Other browsers may their own idiosyncrasies, so you may need to look into the debugging tools for that specific browser if you get real desperate.

XMLHttpRequest Error handlingAnother tool I use to track down errors or just unexpected behavior with AJAX is Fiddler. Remember when working against the localhost you must place a period before the port directive in the URL like this: http://localhost.:23168/errorDemo.aspx. The Fiddler Inspectors tab gives you keen insight to see the exact messages being passed back and forth between the browser and the server.

Finally you can always set break points both in the JavaScript and your server-side code in Visual Studio and step through your code.

Above I show a basic OnPageError event handler, the sample application has a page that deliberately creates an exception in the AJAX call. The service method just throws a new Exception with a custom message, nothing fancy for the demo. The error callback is invoked by the jQuery ajax method. It passes an instance of the XHttpRequest object, an error message and if it was thrown.

 

function

BlowUp() {

wjBlockUI();

ContactServiceProxy.invoke({ serviceMethod:

"BadMethod"

,
callback:

function

(response) { ProcessBlowReturn(response) },
error:

function

(xhr, errorMsg, thrown) {
HandlerBlowUpError(xhr, errorMsg, thrown) }
});
}

So I hope you have a little more insight into how to troubleshoot errors you may be having in your AJAX development. If you have other suggestions I invite you to share them in the comments.

Share This Article With Your Friends!

Googles Ads Facebook Pixel Bing Pixel LinkedIn Pixel