Skip to content

Commit 250c3c1

Browse files
committed
Gracefully handle JSON.parse failures
1 parent ed1b367 commit 250c3c1

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

src/ipinfoWrapper.ts

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,13 @@ export default class IPinfoWrapper {
129129

130130
if (!this.is4xxOr5xx(res.statusCode)) {
131131
res.on("close", () => {
132-
const ipinfo: IPinfo = JSON.parse(data);
132+
let ipinfo: IPinfo;
133+
try {
134+
ipinfo = JSON.parse(data)
135+
} catch {
136+
reject(new Error("error parsing JSON response"));
137+
return;
138+
};
133139

134140
/* convert country code to full country name */
135141
// NOTE: always do this _before_ setting cache.
@@ -230,7 +236,13 @@ export default class IPinfoWrapper {
230236

231237
if (!this.is4xxOr5xx(res.statusCode)) {
232238
res.on("close", () => {
233-
const asnResp: AsnResponse = JSON.parse(data);
239+
let asnResp: AsnResponse;
240+
try {
241+
asnResp = JSON.parse(data)
242+
} catch {
243+
reject(new Error("error parsing JSON response"));
244+
return;
245+
};
234246

235247
/* convert country code to full country name */
236248
// NOTE: always do this _before_ setting cache.
@@ -317,7 +329,15 @@ export default class IPinfoWrapper {
317329

318330
if (!this.is4xxOr5xx(res.statusCode)) {
319331
res.on("close", () => {
320-
resolve(JSON.parse(data));
332+
let response;
333+
try {
334+
response = JSON.parse(data)
335+
} catch {
336+
reject(new Error("error parsing JSON response"));
337+
return;
338+
};
339+
340+
resolve(response);
321341
});
322342

323343
res.on("error", (error: any) => {
@@ -479,7 +499,12 @@ export default class IPinfoWrapper {
479499

480500
const batchPromise = Promise.all(promises).then((values) => {
481501
values.forEach((el: any) => {
482-
let batchResp = JSON.parse(el);
502+
let batchResp;
503+
try {
504+
batchResp = JSON.parse(el);
505+
} catch {
506+
batchResp = {}
507+
};
483508

484509
for (var key in batchResp) {
485510
if (batchResp.hasOwnProperty(key)) {

0 commit comments

Comments
 (0)