【发布时间】:2023-03-23 12:59:01
【问题描述】:
我正在使用 AJAX/JQuery 来调用 WCF 服务。我在服务端有一些 .NET try/catch 错误处理,用于检查用户是否超时,如果有,我会传回 JSON 转换的消息,然后在客户端解析出使用 parseJSON 并使用它将用户重定向回登录页面。 这一切都很好,但我只是从服务返回了一种不同类型的错误,它不是 JSON 格式(它是 XML),所以错误处理函数在尝试解析时在客户端出现了 javascript 错误答复。错误在 jquery.min.js 文件中,并且是“无效字符”错误。
我的问题(最后),如果我不能总是依赖它是 JSON,是否有更好的方法来处理该回复?在 .NET 中,我们有一个可用的 tryParse 方法,它可以在这里很好地工作,但据我所知,JQuery/Javascript 没有这样的功能。如果无法解析回复,则抛出 JS 错误。
这里是引发自定义 JSON 异常的地方:
private HttpSessionState GetUserSession()
{
HttpSessionState session = HttpContext.Current.Session;
try
{
// This is a method we created that checks if user has timed out and throws the exception if so.
SessionBuilder.Create(session, HttpContext.Current.Request, HttpContext.Current.Response);
}
catch (SessionTimeOutException e)
{
throw new WebFaultException<SessionTimeOutException>(new SessionTimeOutException(e.Message), System.Net.HttpStatusCode.BadRequest);
}
return session;
}
这是处理我的 AJAX 请求中的错误的客户端代码:
error: function (HttpRequest)
{
// This is the line that gets the exception because the responseText is a standard .NET XML error, not my custom JSON error.
var parsedReply = $.parseJSON(HttpRequest.responseText);
if (parsedReply.ClassName === "SessionTimeOutException")
{
var url = "../timeout.asp?" + parsedReply.Message;
window.location.href = url;
}
}
【问题讨论】:
-
Javascript 也有
try-catch。 -
是的,我刚刚看到了。哇,不敢相信我已经不知道了。多年来一直是 C# 开发人员,但我对客户端 Web 开发人员仍然很陌生。谢谢
标签: javascript jquery asp.net json ajax