Skip to content

Commit

Permalink
Improve fetch() error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
GarboMuffin committed Jul 22, 2024
1 parent 176df44 commit c405798
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
8 changes: 3 additions & 5 deletions src/safer-fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -43,17 +42,16 @@ 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++;
sleep((failedAttempts + Math.random() - 1) * 5000).then(attemptToFetch);
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();
Expand Down
30 changes: 30 additions & 0 deletions test/unit/tw-get-error.test.js
Original file line number Diff line number Diff line change
@@ -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/
);
});

0 comments on commit c405798

Please sign in to comment.