Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Signaling to jQuery that an AJAX request has failed with a custom error message

Controller: Products and Action: Save, return a JsonResult. If a trapped exception occurs, i would like to signal that error to the client (ie:jQuery) with a custom error message. How can I do that both on the server and client? Can i utilize the function pointer error in this scenario?

Here's the client code

$.ajax({
                url: '/Products/Save',
                type: 'POST',
                dataType: 'json',
                data: ProductJson,
                contentType: 'application/json; charset=utf-8',
                error: function ()
                {
                    //Display some custom error message that was generated from the server
                },
                success: function (data) {
                    // Product was saved! Yay

                }
            });
like image 933
burnt1ce Avatar asked Nov 18 '10 06:11

burnt1ce


1 Answers

The error function that you refer to is called when the request fails (meaning your controller action did not complete successfully; for example, IIS was down when the user made the request). See http://api.jquery.com/jQuery.ajax/.

If your controller action is successfully contacted and you want to let the client know that something happened inside your controller action that was erroneous, you should return a JsonResult that contains an Error or ErrorCode property that your client side JS will understand.

For example, your controller action could look something like this:

public ActionResult Save()
{
   ActionResult result;
   try 
   {
      // An error occurs
   }
   catch(Exception)
   {
      result = new JsonResult() 
      { 
        // Probably include a more detailed error message.
        Data = new { Error = true, ErrorMessage = "Product could not be saved." } 
      };
   }
   return result;
}

And you would write the following JavaScript to parse that error:

$.ajax({
  url: '/Products/Save',
   'POST',
   'json',
   ProductJson,
   'application/json; charset=utf-8',
   error: function ()
   {
      //Display some custom error message that was generated from the server
   },
   success: function (data) {
      if (data.Error) {
         window.alert(data.ErrorMessage);
      }
      else {
         // Product was saved! Yay
      }
   }
});

Hope that helps.

like image 72
Andrew Whitaker Avatar answered Sep 28 '22 05:09

Andrew Whitaker