Skip to content
This repository was archived by the owner on Oct 10, 2022. It is now read-only.

Commit 92f628f

Browse files
committed
Fix error messages when the error response is not JSON
1 parent 40d4590 commit 92f628f

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

src/methods/response.js

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,13 @@ const { JSONHTTPError, TextHTTPError } = require('micro-api-client')
22

33
// Read and parse the HTTP response
44
const parseResponse = async function(response) {
5-
const { method, ErrorType } = getResponseType(response)
6-
const parsedResponse = await response[method]()
5+
const responseType = getResponseType(response)
6+
const textResponse = await response.text()
7+
8+
const parsedResponse = parseJsonResponse(response, textResponse, responseType)
79

810
if (!response.ok) {
11+
const ErrorType = responseType === 'json' ? JSONHTTPError : TextHTTPError
912
throw new ErrorType(response, parsedResponse)
1013
}
1114

@@ -16,10 +19,22 @@ const getResponseType = function({ headers }) {
1619
const contentType = headers.get('Content-Type')
1720

1821
if (contentType != null && contentType.includes('json')) {
19-
return { method: 'json', ErrorType: JSONHTTPError }
22+
return 'json'
23+
}
24+
25+
return 'text'
26+
}
27+
28+
const parseJsonResponse = function(response, textResponse, responseType) {
29+
if (responseType === 'text') {
30+
return textResponse
2031
}
2132

22-
return { method: 'text', ErrorType: TextHTTPError }
33+
try {
34+
return JSON.parse(textResponse)
35+
} catch (error) {
36+
throw new TextHTTPError(response, textResponse)
37+
}
2338
}
2439

2540
const getFetchError = function(error, url, opts) {

0 commit comments

Comments
 (0)