Skip to content

Commit a26ff5c

Browse files
committed
refactor: Add information to API errors
1 parent 138aab2 commit a26ff5c

File tree

2 files changed

+20
-14
lines changed

2 files changed

+20
-14
lines changed

__tests__/ipinfoWrapper.test.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,4 +184,9 @@ describe("IPinfoWrapper", () => {
184184
expect(data.ip).toEqual("198.51.100.1");
185185
expect(data.bogon).toEqual(true);
186186
});
187+
188+
test("Error is thrown for invalid token", async () => {
189+
const ipinfo = new IPinfoWrapper("invalid-token");
190+
await expect(ipinfo.lookupIp("1.2.3.4")).rejects.toThrow();
191+
});
187192
});

src/ipinfoWrapper.ts

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -28,18 +28,6 @@ import VERSION from "./version";
2828
const clientUserAgent = `IPinfoClient/nodejs/${VERSION}`;
2929
const countryFlagURL = "https://cdn.ipinfo.io/static/images/countries-flags/";
3030

31-
function checkResponseForError(response: Response) {
32-
if (response.statusCode === 429) {
33-
throw new ApiLimitError();
34-
}
35-
36-
if (response.statusCode >= 400) {
37-
throw new Error("Response is not OK.");
38-
}
39-
40-
return response;
41-
}
42-
4331
export default class IPinfoWrapper {
4432
private token: string;
4533
private baseUrl: string;
@@ -131,7 +119,21 @@ export default class IPinfoWrapper {
131119
);
132120

133121
return fetch(`${this.baseUrl}${path}`, request).then(
134-
checkResponseForError
122+
(response: Response) => {
123+
if (response.status === 429) {
124+
throw new ApiLimitError();
125+
}
126+
127+
if (response.status >= 400) {
128+
throw new Error(
129+
`Received an error from the IPinfo API ` +
130+
`(using authorization ${headers["Authorization"]}) ` +
131+
`${response.status} ${response.statusText} ${response.url}`
132+
);
133+
}
134+
135+
return response;
136+
}
135137
);
136138
}
137139

@@ -195,7 +197,6 @@ export default class IPinfoWrapper {
195197
return data;
196198
}
197199

198-
// TODO: Return type?
199200
return this.fetchApi(`${asn}/json`).then(async (response) => {
200201
const asnResp = (await response.json()) as AsnResponse;
201202

0 commit comments

Comments
 (0)