views:

299

answers:

1

I use $.ajax function to interact with a regular asp.net web service. My question is how do I trap errors. The web service interacts with the database and returns errors if any are encountered, but after this point, it becomes very unclear how do i trap these errors (plus others encountered during $.ajax performance).

$.ajax has callback failure with one argument msg. Do I have to do something on the web service side to populate that msg variable with the error from the database?

Could someone outline the steps I need to take in my code in order to use Jquery + ASP.net web service for a robust communication?

Thanks!

 var list = [["john.doe", "corp"],["1","2","3","7"],["4","5","6"],["34","88","898"]];
         var jsonText = JSON.stringify({ list: list });

         $.ajax({
             type: "POST",
             url: "http://localhost/TemplateWebService/TemplateWebService/Service.asmx/SaveSampleTemplate",
             data: jsonText,
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             success: function(response) {

             alert("success!");

                 alert(response.d);


             },

             failure: function(msg) {

                 alert("fail");

                 $('#pnlOutput').append('<p><font color="red">Message error ' + msg + ' </font></p>');

             }

         });

    }
+1  A: 

I believe that the error callback function is called anytime the server responds with with something other than a status of '200'. So if there is an exception thrown on the server, or network issues, then the callback will run.

If you want to output something via the error callback you'll have to set the server response to something other than '200'.

Depending on what you're trying to do you may want to be careful with this, as you are blurring the line between a true server/network error and part of your business logic.

Hope it helps!

EDIT: Check out the documentation here under the Options tab for more info.

Justin Swartsel
Thanks I saw that page.My question was however, more to do with how do I effectively show the database errors to the user. I woudn't meddle with server response, so the way to do it for me would be to get the response object to return a database error. To achieve that I would set the return object inside my web service to return an error instead of the results. Is that the right idea?
gnomixa
That sounds like the right idea... but i'm not sure the best way to go about it. You might try catching exceptions on the server and throwing a new exeption (custom or otherwise) with a tidier message to your users.
Justin Swartsel
i would grab the errors inside the web service, then wrap it and shove it into a return object, then on success callback (remember that this is a database error, so error callback shouldn't be invoked), I would unpack it and show it to the user.
gnomixa