Javascript jquery对web方法的AJAX调用未运行错误函数
我在jquery中调用的aspx页面上有一个WebMethod,我试图让它在弹出框中显示抛出异常的消息,但调试器没有在error函数下运行代码,而是停止说“用户未处理异常”。如何将错误返回到客户端Javascript jquery对web方法的AJAX调用未运行错误函数,javascript,c#,jquery,asp.net,ajax,Javascript,C#,Jquery,Asp.net,Ajax,我在jquery中调用的aspx页面上有一个WebMethod,我试图让它在弹出框中显示抛出异常的消息,但调试器没有在error函数下运行代码,而是停止说“用户未处理异常”。如何将错误返回到客户端 [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static void SubmitSections(string item) { try {
[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状态代码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代码>(无参数) 好的,我明白了。当你说返回一个错误时,你的意思是返回一个包含错误信息的字符串吗?如何获取错误:要执行的函数?@KateMak返回新的httpstatuscodesult(errorCode,“Message”);如果您愿意,错误代码可能是500。@KateMak听到这个消息我很难过。您是否删除了Try/Catch?你能编辑你的问题并给我看服务器端代码吗?谢谢。@KateMak要获得WebMethod,请尝试以下方法:HttpContext.Current.Response.StatusCode=500;是的,尝试了一下,但我仍然没有看到我在那里输入的错误消息。相反,我的警报框看起来像:请求:[对象]状态:错误错误:内部服务器错误