【问题标题】:jquery AJAX call to web method not running error functionjquery AJAX 调用 web 方法未运行错误函数
【发布时间】:2014-10-02 21:59:19
【问题描述】:

我在 jquery 中调用的 aspx 页面上有一个 WebMethod,我试图让它在弹出框中显示引发异常的消息,但不是在错误函数下运行代码,而是在调试器停止说“用户未处理的异常”。如何将错误返回给客户端?

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static void SubmitSections(string item)
    {
        try
        {
            throw new Exception("Hello");
        }

        catch (Exception ex)
        {
            HttpContext.Current.Response.Write(ex.Message);
            throw new Exception(ex.Message, ex.InnerException);
        }
    }

在我的 js 文件中:

$.ajax({
    type: "POST",
    url: loc + "/SubmitSections",
    data: dataValue,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (Result) {
        $("#modal-submitting").modal('hide');
        document.location = nextPage;
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        $("#modal-submitting").modal('hide');
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    }
});//ajax call end

【问题讨论】:

标签: javascript c# jquery asp.net ajax


【解决方案1】:

您应该返回一个错误,例如 Http 状态代码 500,在客户端作为错误进行处理。

服务器端的抛出错误不会返回到客户端。

对于 WebMethod,您应该设置 Response.StatusCode。

HttpContext.Current.Response.StatusCode = 500; 

【讨论】:

  • 好的,我明白了。当您说返回错误时,您的意思是返回一个包含错误消息的字符串吗?我怎样才能得到错误:function() to execute?
  • @KateMak return new HttpStatusCodeResult(errorCode, "Message");如果您愿意,errorCode 可以是 500。
  • @KateMak 很遗憾听到这个消息。您是否删除了 Try/Catch?你能编辑你的问题并向我展示服务器端代码吗?谢谢。
  • @KateMak 对于 WebMethod,试试这个:HttpContext.Current.Response.StatusCode = 500;
  • 是的,试了一下,但我仍然没有看到我放在那里的错误消息。相反,我的警报框看起来像:请求:[对象对象]状态:错误错误:内部服务器错误
【解决方案2】:

我认为您的问题是您正在从客户端脚本发出 JSON 请求,但您的 catch 块只是将文本写入响应,而不是 JSON,因此客户端错误函数不会触发。

尝试使用 Newtonsoft.Json 等库将 .NET 类转换为 JSON 响应。然后,您可以创建一些简单的包装类来表示响应数据,例如:-

[Serializable]
public class ResponseCustomer
{
    public int ID;
    public string CustomerName;
}

[Serializable]
public class ResponseError
{
    public int ErrorCode;
    public string ErrorMessage;
}

在你的 catch 块中..

var json = JsonConvert.SerializeObject(new ResponseError 
                                           { 
                                              ErrorCode = 500, 
                                              ErrorMessage = "oh no !" 
                                           });
context.Response.Write(json);

顺便说一句: throw new Exception(...) 不是推荐的做法,因为你会丢失堆栈跟踪,这对调试或日志记录没有帮助。如果您需要重新抛出异常,推荐的做法是调用throw;(无参数)。

【讨论】:

    猜你喜欢
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 2019-01-08
    • 2017-06-10
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多