代码之家  ›  专栏  ›  技术社区  ›  burnt1ce

ASP.NET MVC:向jQuery发送AJAX请求失败的信号,并显示自定义错误消息

  •  5
  • burnt1ce  · 技术社区  · 14 年前

    Controller:Products和Action:Save,返回一个JsonResult。如果发生被捕获的异常,我想用自定义错误消息向客户端(即:jQuery)发送该错误。如何在服务器和客户端上都这样做?在这种情况下,我能利用函数指针错误吗?

    这是客户代码

    $.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
    
                    }
                });
    
    2 回复  |  直到 12 年前
        1
  •  5
  •   Andrew Whitaker    11 年前

    这个 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
          }
       }
    });
    

    希望能有所帮助。

        2
  •  0
  •   The Coder    13 年前

    我使用了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;
        }
    }