[英]jquery AJAX call to web method not running error function
我在 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
您应该返回一个错误,例如Http Status Code 500,以作为错误在客户端进行处理。
服务器端的抛出错误不会返回给客户端。
对于WebMethod,您应该设置Response.StatusCode。
HttpContext.Current.Response.StatusCode = 500;
我认为您的问题是您正在从客户端脚本发出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;
}
并在您的捕获块中。
var json = JsonConvert.SerializeObject(new ResponseError
{
ErrorCode = 500,
ErrorMessage = "oh no !"
});
context.Response.Write(json);
顺便说一句:不建议您throw new Exception(...)
因为您将丢失堆栈跟踪,这对调试或日志记录无济于事。 如果需要重新抛出异常,建议的做法是只调用throw;
(无参数)。
JQuery xhr 将在 responseText/responseJSON 属性中返回错误和堆栈跟踪。
例如:C#:
throw new Exception("Error message");
Javascript:
$.ajax({
type: "POST",
url: "./Default.aspx/GetData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxFailed (jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseJSON.Message);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.