Skip to content

Commit 5f723b9

Browse files
committed
Merge branch 'try-catch-json-parse' of github.com:commercetools/nodejs into try-catch-json-parse
2 parents c3c705b + 047831f commit 5f723b9

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed

packages/sdk-middleware-http/src/http.js

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,10 @@ export default function createHttpMiddleware({
100100
let abortController: any
101101
if (timeout || getAbortController || _abortController)
102102
// eslint-disable-next-line
103-
abortController = (getAbortController ? getAbortController(): null) || _abortController || new AbortController()
103+
abortController =
104+
(getAbortController ? getAbortController() : null) ||
105+
_abortController ||
106+
new AbortController()
104107

105108
const url = host.replace(/\/$/, '') + request.uri
106109
const body =
@@ -153,17 +156,31 @@ export default function createHttpMiddleware({
153156
}
154157

155158
res.text().then((result: Object) => {
156-
let resBody
157-
159+
// Try to parse the response as JSON
160+
let parsed
158161
try {
159-
resBody = result.length > 0 ? JSON.parse(result) : {}
162+
parsed = result.length > 0 ? JSON.parse(result) : {}
160163
} catch (err) {
161-
resBody = result
164+
if (enableRetry && retryCount < maxRetries) {
165+
setTimeout(
166+
executeFetch,
167+
calcDelayDuration(
168+
retryCount,
169+
retryDelay,
170+
maxRetries,
171+
backoff,
172+
maxDelay
173+
)
174+
)
175+
retryCount += 1
176+
return
177+
}
178+
parsed = result
162179
}
163180

164181
const parsedResponse: Object = {
165182
...response,
166-
body: resBody,
183+
body: parsed,
167184
statusCode: res.status,
168185
}
169186

packages/sdk-middleware-http/test/http.spec.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ describe('Http', () => {
7070
httpMiddleware(next)(request, response)
7171
}))
7272

73-
test('execute a get request which give not json response', () =>
73+
test("execute a get request which doesn't return a json response", () =>
7474
new Promise((resolve, reject) => {
7575
const request = createTestRequest({
7676
uri: '/foo/bar',

0 commit comments

Comments
 (0)