Skip to content

Commit a061f27

Browse files
author
Crhistian Ramirez
committed
fix: invalid character in error responses' JSON #40
1 parent 50af835 commit a061f27

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

src/Sdk.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,35 @@
1111
*
1212
*/
1313

14+
15+
// ordercloud's error responses have a BOM character that causes json parse to fail
16+
function customJsonParser(res, fn) {
17+
res.text = '';
18+
res.setEncoding('utf8');
19+
res.on('data', function(chunk) {
20+
res.text += chunk;
21+
})
22+
res.on('end', function() {
23+
var body;
24+
var err;
25+
try {
26+
var text = res.text;
27+
if(text && text.charCodeAt(0) === 65279) {
28+
text = text.substr(1)
29+
}
30+
body = text && JSON.parse(text);
31+
} catch (err2) {
32+
err = err2;
33+
// issue #675: return the raw response if the response parsing fails
34+
err.rawResponse = res.text || null;
35+
// issue #876: return the http status code if the response parsing fails
36+
err.statusCode = res.statusCode;
37+
} finally {
38+
fn(err, body);
39+
}
40+
})
41+
}
42+
1443
(function(root, factory) {
1544
if (typeof define === 'function' && define.amd) {
1645
// AMD. Register as an anonymous module.
@@ -344,6 +373,8 @@
344373
var _this = this;
345374
var url = this.buildUrl(path, pathParams);
346375
var request = superagent(httpMethod, url);
376+
request.parse(customJsonParser);
377+
request.buffer(true)
347378

348379
// apply authentications
349380
this.applyAuthToRequest(request, accessToken);
@@ -415,6 +446,8 @@ exports.prototype.callAuth = function callApi(path, httpMethod, pathParams,
415446
var _this = this;
416447
var url = _this.baseAuthPath.replace(/\/+$/, '') + path;
417448
var request = superagent(httpMethod, url);
449+
request.parse(customJsonParser);
450+
request.buffer(true)
418451

419452
// set query parameters
420453
request.query(this.normalizeParams(queryParams));

0 commit comments

Comments
 (0)