Wednesday, August 6, 2014

catch errors with jQuery's .ajax

Per the REST spec DELETE and PUT should be implemented in a fire and forget manner. (It is POST and GET which return data.) If you're not going to get anything back upon success however, how will you know if something goes wrong? Well, you can still catch an error in a jQuery .ajax implementation like so:

$.ajax({
   type: "DELETE",
   url: '/api/Person?identity=' + $('#FlatIdentity').val(),
   dataType: 'json',
   success: function () {
      isBlinkingDeleteAccountButton = false;
      window.location = "/home/exit/";
   },
   error: function (request, status, error) {
      var responseText = JSON.parse(request.responseText);
      $('#DeleteAccountError').html(responseText.ExceptionMessage);
   }
});

 
 

My code reaches out to an ASP.NET MVC Web API controller action. I, when applicable, throw exceptions therein like so:

throw new Exception("Sad trombone.");

No comments:

Post a Comment