Search code examples
javascriptjsonmeteorhttprequesthttpexception

Parsing erroneous server responses in Meteor


We are developing a Meteor app which is calling in-house made RESTful API. Our server expects that "Content-type: application/json" header is set and it always responds with same header (Content-Type: application/json; charset=UTF-8) and a JSON-formatted body, no matter the status code.

Few examples:

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

In Meteor, we are using a method like this to call 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;

The problem here is when server responds with 4xx/5xx errors, the exc object is not a proper JSON-formatted object (we are trying this with Meteor 1.2 and 1.3), but it looks like this:

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

In case of 200 response, the result is a proper JSON object and we can parse it with no problems.

We tried to change our server call to Meteor's async call and in that case everything works fine - we can access error object's headers and content and parse it properly.

My question is: why is the response wrapped around { [Error: failed [400] {"original_response": "here"}] stack: [Getter] } and how to properly parse the error in this case? Are we missing some header somewhere (server or Meteor app) in order to Meteor properly constructs exc object when it gets erroneous response?


Solution

  • Well, apparently Meteor v1.3 is wrapping the exception in a different way, so in my case, the object in the exception can be accessed with exc.response now...