Skip to content

Commit 408c062

Browse files
Merge pull request #23 from balena-io-modules/non-json
Avoid issues with non-JSON responses
2 parents 6fd9124 + 9901631 commit 408c062

File tree

1 file changed

+17
-8
lines changed

1 file changed

+17
-8
lines changed

src/index.ts

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,24 @@ export default class PineFetch<
4444
body: normalizedBody,
4545
});
4646

47+
let responseBody;
48+
try {
49+
// Fetch the response as text
50+
responseBody = await response.text();
51+
// And then try to parse it as JSON as it is likely to be JSON
52+
responseBody = JSON.parse(responseBody);
53+
// TODO: base this upon the returned content-type header
54+
} catch {
55+
// empty
56+
}
57+
4758
if (response.status >= 400) {
48-
let responseBody = 'Unknown error';
49-
try {
50-
responseBody = await response.text();
51-
} catch {
52-
// empty
53-
}
54-
throw new RequestError(responseBody, response.status, response.headers);
59+
throw new RequestError(
60+
responseBody ?? 'Unknown error',
61+
response.status,
62+
response.headers,
63+
);
5564
}
56-
return await response.json();
65+
return responseBody;
5766
}
5867
}

0 commit comments

Comments
 (0)