1

我想将 C# 中的自定义错误设置为显示而不是xhr.responseText现在的默认错误。如何传递cSharpErrorMessage给ajax错误?

这是我的 C# 代码:

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static AjaxResult<string> GetAutoCompleteHtml(string termList)
        {
            const string cSharpErrorMessage = "Unable to generate autocomplete HTML.";

            try
            {
                //some logic
            }
            catch (Exception ex)
            {
                //some logic
            }
        }

这是我的ajax函数:

function StartAutoCompleteSearch(termsList) {
    if (termsList.length > 2) {
        $.ajax({
            url: '/Ajax/AjaxCalls.aspx/GetAutoCompleteHtml',
            type: 'POST',
            data: "{'termList':'" + termsList + "'}",
            global: false,
            datatype: JSON,
            success: function(response) {
                //some logic
            },
            error: function(xhr, response) {
                var err = eval("(" + xhr.responseText + ")");
                alert(err.Message + " Click OK to log back in ");
                window.location = "/login";
            }
        });
    }
} 
4

1 回答 1

1

只是抛出一个异常。像这样:

throw new Exception(cSharpErrorMessage);

您的代码示例:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
 public static AjaxResult<string> GetAutoCompleteHtml(string termList)
 {
      const string cSharpErrorMessage = "Unable to generate autocomplete HTML.";

      try
      {
                //some logic
      }
      catch (Exception ex)
      {
                //some logic to clean up and then throw exception
                throw new Exception(cSharpErrorMessage);
       }
   }

如果您需要在 ajax 调用中将错误消息显示为第三个参数,请尝试以下操作:

HttpContext.Current.Response.StatusCode = 500;
HttpContext.Current.Response.StatusDescription = cSharpErrorMessage;
HttpContext.Current.Response.End();

你的脚本:

error: function(xhr, response,errorThrown) {
                alert(errorThrown + " Click OK to log back in ");
                window.location = "/login";
            }
于 2013-06-25T07:30:50.703 回答