2016-04-07 27 views
2

我們正在開發一個Meteor應用程序,它調用內部製作的RESTful API。我們的服務器預計"Content-type: application/json"標頭已設置,並且始終以相同的標頭(Content-Type: application/json; charset=UTF-8)和JSON格式的主體響應,無論狀態碼如何。解析Meteor中的錯誤服務器響應

幾個例子:

# 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" 
} 

流星,我們使用這樣的方法來調用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對象?

+0

流星拋出一個錯誤4xx/5xx響應,您的服務器響應在錯誤中,您可以解析錯誤字符串並獲取JSON數據。檢查文檔,似乎使用異步回調不會拋出錯誤,那麼你也許可以得到結果:http://docs.meteor.com/#/full/http – ojovirtual

+0

啊,是的,我忘了提及我們嘗試使用異步調用,我會用這個信息更新我的帖子:) – errata

回答

1

嗯,顯然流星V1.3被包裝以不同的方式外,所以在我的情況下,異常的對象,可以用exc.response現在訪問......當有