diff --git a/packages/cache/src/fetchwithcache.test.ts b/packages/cache/src/fetchwithcache.test.ts index 4062fe48..ce6b3d8b 100644 --- a/packages/cache/src/fetchwithcache.test.ts +++ b/packages/cache/src/fetchwithcache.test.ts @@ -327,4 +327,26 @@ describe('`fetchWithCache`', () => { mockFetch.restore() expect(mockFetch.fulfilled).toBe(true) }) + + test('Does not throw an error when response returns a 5xx error', async () => { + const mockFetch = new MockFetch() + .get({ + url: 'https://example.netlify/.netlify/cache/https%3A%2F%2Fnetlify.com%2F', + response: new Response(null, { status: 404 }), + }) + .get({ + url: 'https://netlify.com/', + response: new Response('Internal Server Error', { status: 500 }), + }) + .inject() + const resourceURL = 'https://netlify.com' + + const response = await fetchWithCache(resourceURL) + + expect(response.status).toBe(500) + expect(await response.text()).toBe('Internal Server Error') + + mockFetch.restore() + expect(mockFetch.fulfilled).toBe(true) + }) }) diff --git a/packages/cache/src/fetchwithcache.ts b/packages/cache/src/fetchwithcache.ts index ae50c6fa..1efa3896 100644 --- a/packages/cache/src/fetchwithcache.ts +++ b/packages/cache/src/fetchwithcache.ts @@ -136,7 +136,10 @@ export const fetchWithCache: FetchWithCache = async ( const cacheResponse = new Response(cacheStream, fresh) applyHeaders(cacheResponse.headers, cacheHeaders(cacheSettings)) - const cachePut = cache.put(request, cacheResponse) + const cachePut = cache.put(request, cacheResponse).catch(() => { + // If we fail to cache the response, we want to swallow the error because + // we'll still return the result of `fetch`. + }) if (onCachePut) { await onCachePut(cachePut)