2

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

几个例子:

# 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 应用程序)遗漏了一些标头,以便 Meteorexc在收到错误响应时正确构造对象?

4

1 回答 1

1

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

于 2016-05-12T13:24:36.490 回答