Skip to content

Commit dfcc0bc

Browse files
Aaron Cookkatspaugh
andauthored
fix: prevent parsing empty responses from throwing (#105)
* fix: prevent parsing empty responses from throwing * fix: guard empty JSON + check length of content * fix: remove `try/catch` * fix: adjust error text Co-authored-by: katspaugh <381895+katspaugh@users.noreply.github.com> * fix: throw when invalid content Co-authored-by: katspaugh <381895+katspaugh@users.noreply.github.com>
1 parent 95a32a8 commit dfcc0bc

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

src/utils.ts

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@ export type ErrorResponse = {
77
message: string
88
}
99

10+
const isErrorResponse = (data: unknown): data is ErrorResponse => {
11+
const isObject = typeof data === 'object' && data !== null
12+
return isObject && 'code' in data && 'message' in data
13+
}
14+
1015
function replaceParam(str: string, key: string, value: string): string {
1116
return str.replace(new RegExp(`\\{${key}\\}`, 'g'), value)
1217
}
@@ -51,16 +56,18 @@ export async function fetchData<T>(url: string, body?: unknown): Promise<T> {
5156
}
5257

5358
const resp = await fetch(url, options)
54-
const json = await resp.json()
59+
let json
5560

56-
if (!resp.ok) {
57-
let errTxt = ''
58-
try {
59-
const err = json as ErrorResponse
60-
errTxt = `${err.code}: ${err.message}`
61-
} catch (e) {
62-
errTxt = resp.statusText
61+
try {
62+
json = await resp.json()
63+
} catch {
64+
if (resp.headers && resp.headers.get('content-length') !== '0') {
65+
throw new Error(`Invalid response content: ${resp.statusText}`)
6366
}
67+
}
68+
69+
if (!resp.ok) {
70+
const errTxt = isErrorResponse(json) ? `${json.code}: ${json.message}` : resp.statusText
6471
throw new Error(errTxt)
6572
}
6673

0 commit comments

Comments
 (0)