【问题标题】:Parsing erroneous server responses in Meteor在 Meteor 中解析错误的服务器响应
【发布时间】:2016-07-28 06:46:57
【问题描述】:

我们正在开发一个调用内部制作的 RESTful API 的 Meteor 应用程序。我们的服务器期望 "Content-type: application/json" 标头已设置,并且无论状态码如何,它始终以相同的标头 (Content-Type: application/json; charset=UTF-8) 和 JSON 格式的正文进行响应。

几个例子:

# SERVER RESPONDED WITH 200:
HTTP/1.1 200 OK
Content-Length: 338
Content-Type: application/json; charset=UTF-8
Date: Thu, 07 Apr 2016 10:44:33 GMT
Server: nginx

{
    "result": "Hello, world!",
    "status": "OK"
}


# RESPONSE WITH SOME ERRORS:
HTTP/1.1 400 Bad Request
Content-Length: 547
Content-Type: application/json; charset=UTF-8
Date: Thu, 07 Apr 2016 10:23:49 GMT
Server: nginx

{
    "errors": [
        {
            "description": "error desc.",
            "location": "error location",
            "name": "error name"
        }
    ],
    "status": "error"
}

在 Meteor 中,我们使用这样的方法来调用 API:

let url = 'https://server.url/path';
var auth = "user:pass";
var headers = {"Content-type": "application/json"};

let objId = 100;
let report_type = 'some_type';
let data = {
    object_id: objId,
    report_type: report_type
};
let payload = {auth, headers, data};
try {
    var result = HTTP.post(url, payload);
} catch (exc) {
    console.log(exc);
    return exc;
}
return result;

这里的问题是,当服务器响应 4xx/5xx 错误时,exc 对象不是正确的 JSON 格式对象(我们正在尝试使用 Meteor 1.2 和 1.3),但它看起来像这样:

{ [Error: failed [400] {"errors": [{"description": "error desc.", "location": "error location", "name": error name"}], "status": "error"}] stack: [Getter] }

在 200 响应的情况下,result 是一个正确的 JSON 对象,我们可以毫无问题地解析它。

我们尝试将服务器调用更改为 Meteor 的异步调用,在这种情况下一切正常 - 我们可以访问错误对象的 headerscontent 并正确解析它。

我的问题是:为什么响应围绕{ [Error: failed [400] {"original_response": "here"}] stack: [Getter] } 以及在这种情况下如何正确解析错误?我们是否在某处(服务器或 Meteor 应用程序)遗漏了一些标头,以便 Meteor 在收到错误响应时正确构造 exc 对象?

【问题讨论】:

  • Meteor 在有 4xx/5xx 响应时会抛出错误,您的服务器响应在错误内,您可以解析错误字符串并获取 JSON 数据。检查文档,似乎使用异步回调不会抛出错误,那么您可能会得到结果:docs.meteor.com/#/full/http
  • 啊,是的,我忘了提到我们尝试使用异步调用,我会用这些信息更新我的帖子:)

标签: javascript json meteor httprequest httpexception


【解决方案1】:

好吧,显然 Meteor v1.3 正在以不同的方式包装异常,所以在我的情况下,现在可以使用 exc.response 访问异常中的对象...

【讨论】:

    猜你喜欢
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    相关资源
    最近更新 更多