From c405798f8c39a65823704791f854231d99e298ce Mon Sep 17 00:00:00 2001 From: Muffin Date: Sun, 21 Jul 2024 23:12:07 -0500 Subject: [PATCH] Improve fetch() error messages --- src/safer-fetch.js | 8 +++----- test/unit/tw-get-error.test.js | 30 ++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) create mode 100644 test/unit/tw-get-error.test.js diff --git a/src/safer-fetch.js b/src/safer-fetch.js index 44f78779..3bd5555b 100644 --- a/src/safer-fetch.js +++ b/src/safer-fetch.js @@ -11,7 +11,6 @@ const queue = []; const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); const startNextFetch = ([resolve, url, options]) => { - let firstError; let failedAttempts = 0; /** @@ -43,9 +42,6 @@ const startNextFetch = ([resolve, url, options]) => { // if we send too many at once (as we do). console.warn(`Attempt to fetch ${url} failed`, error); - if (!firstError) { - firstError = error; - } if (failedAttempts < 2) { failedAttempts++; @@ -53,7 +49,9 @@ const startNextFetch = ([resolve, url, options]) => { return; } - done(Promise.reject(firstError)); + // The fetch() error is usually very generic, so we'll add enough information + // to possibly be useful. + done(Promise.reject(new Error(`Storage request ${url} failed: ${error}`))); }); attemptToFetch(); diff --git a/test/unit/tw-get-error.test.js b/test/unit/tw-get-error.test.js new file mode 100644 index 00000000..8ef62a6f --- /dev/null +++ b/test/unit/tw-get-error.test.js @@ -0,0 +1,30 @@ +jest.mock('cross-fetch', () => { + const crossFetch = jest.requireActual('cross-fetch'); + const mockFetch = () => Promise.reject(new Error('Intentional error for testing')); + return { + ...crossFetch, + default: mockFetch, + fetch: mockFetch + }; +}); + +const FetchTool = require('../../src/FetchTool'); + +jest.setTimeout(15000); + +test('get() returns a somewhat useful error message', async () => { + const tool = new FetchTool(); + + let error = null; + try { + await tool.get({ + url: 'https://something.turbowarp.org/1234.png' + }); + } catch (e) { + error = e; + } + + expect(error.toString()).toMatch( + /Storage request https:\/\/something.turbowarp.org\/1234.png failed: Error: Intentional error for testing/ + ); +});