views:

194

answers:

2

I am on the look out for an accepted solution for trapping errors in the following scenario: i have an asp.net web services that interacts with the database. I interact with the web service through jquery's $ajax function.

I would like to know what is the accepted stable methodology for error trapping. When the data is received from the the web service there are two types of errors in my scenario:

  • db errors
  • ajax errors

Ajax errors can trapped inside error portion of $ajax function. I trap the database errors inside the web service and so far I could only come up with one idea how to pass them on to the user - pack them in the results array. But this solution is awkward. Are there any better ideas?

Here is the sample of code I use for accessing asp.net web service:

$.ajax({
    type: "POST",

    url: "http://localhost/WebServices/Service.asmx/GetBillingEntities",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(response) {
        var results = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

       DisplayResults();


    },

    error: function(xhr, status, error) {
        // Display a generic error for now.
        alert("AJAX Error!");
    }

});

So should the database results go in to results array and unpacked there manually? Is there a better system? Thanks!

A: 

What you can do is throw an exception in your GetBillingEntities method of your webservice. Catch the exception, log some details and then re-throw it. If your method throws an exception it should get caught in the "error:" block.

So basically you handle the error data in your service and handle how to display an error to the user in your "error:" block.

brendan
but how do i distinguish between database and ajax errors at this point? Is there a way to set error message/error status inside web service in order to show up in the error block? do you have a piece of code to demonstrate it?Thanks!
gnomixa
+1  A: 

got it:

$(document).ready(function() {
02      $.ajax({
03          type: "GET",
04          url: "AJAX/DivideByZero",
05          dataType: "json",
06          success: function(data) {
07              if (data) {
08                  alert("Success!!!");
09              }
10          }, error: function(xhr, status, error) {
11              DisplayError(xhr);
12          }
13      });
14  });
15   
16  function DisplayError(xhr) {
17      var msg = JSON.parse(xhr.responseText);
18      alert(msg.Message);
19  }
gnomixa