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

Controller: Products and actions: Save, return JsonResult. If an exception occurs in the trap, I would like to report this error to the client (i.e. jQuery) with a custom error message. How can I do this both on the server and on the client? Can I use a function pointer error in this script?

Here is customer 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

                }
            });
+5
source share
2 answers

error, , , ( , , , IIS , ). . http://api.jquery.com/jQuery.ajax/.

, , - , , JsonResult, error ErrorCode, JS .

, :

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;
}

JavaScript, :

$.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
      }
   }
});

, .

+5

clientError, , ​​ , 500 ( jQuery , , :

/// <summary>Catches an Exception and returns just the message as plain text - to avoid full Html 
/// messages on the client side.</summary>
public class ClientErrorAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        var response = filterContext.RequestContext.HttpContext.Response;
        response.Write(filterContext.Exception.Message);
        response.ContentType = MediaTypeNames.Text.Plain;
        response.StatusCode = (int)HttpStatusCode.InternalServerError; 
        response.StatusDescription = filterContext.Exception.Message;
        filterContext.ExceptionHandled = true;
    }
}
0

All Articles