Skip to content

Commit 2a4da13

Browse files
fix: make fetchWithCache stop throwing on uncacheable response (#481)
1 parent 6eff819 commit 2a4da13

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

packages/cache/src/fetchwithcache.test.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,4 +327,26 @@ describe('`fetchWithCache`', () => {
327327
mockFetch.restore()
328328
expect(mockFetch.fulfilled).toBe(true)
329329
})
330+
331+
test('Does not throw an error when response returns a 5xx error', async () => {
332+
const mockFetch = new MockFetch()
333+
.get({
334+
url: 'https://example.netlify/.netlify/cache/https%3A%2F%2Fnetlify.com%2F',
335+
response: new Response(null, { status: 404 }),
336+
})
337+
.get({
338+
url: 'https://netlify.com/',
339+
response: new Response('Internal Server Error', { status: 500 }),
340+
})
341+
.inject()
342+
const resourceURL = 'https://netlify.com'
343+
344+
const response = await fetchWithCache(resourceURL)
345+
346+
expect(response.status).toBe(500)
347+
expect(await response.text()).toBe('Internal Server Error')
348+
349+
mockFetch.restore()
350+
expect(mockFetch.fulfilled).toBe(true)
351+
})
330352
})

packages/cache/src/fetchwithcache.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,10 @@ export const fetchWithCache: FetchWithCache = async (
136136
const cacheResponse = new Response(cacheStream, fresh)
137137
applyHeaders(cacheResponse.headers, cacheHeaders(cacheSettings))
138138

139-
const cachePut = cache.put(request, cacheResponse)
139+
const cachePut = cache.put(request, cacheResponse).catch(() => {
140+
// If we fail to cache the response, we want to swallow the error because
141+
// we'll still return the result of `fetch`.
142+
})
140143

141144
if (onCachePut) {
142145
await onCachePut(cachePut)

0 commit comments

Comments
 (0)