diff --git a/web3.js/src/connection.ts b/web3.js/src/connection.ts index 3ec1ce6dc4..dd4b592d8b 100644 --- a/web3.js/src/connection.ts +++ b/web3.js/src/connection.ts @@ -760,19 +760,24 @@ function createRpcClient( agentManager = new AgentManager(useHttps); } - let fetchWithMiddleware: (url: string, options: any) => Promise; + let fetchWithMiddleware: + | ((url: string, options: any) => Promise) + | undefined; if (fetchMiddleware) { - fetchWithMiddleware = (url: string, options: any) => { - return new Promise((resolve, reject) => { - fetchMiddleware(url, options, async (url: string, options: any) => { + fetchWithMiddleware = async (url: string, options: any) => { + const modifiedFetchArgs = await new Promise<[string, any]>( + (resolve, reject) => { try { - resolve(await fetch(url, options)); + fetchMiddleware(url, options, (modifiedUrl, modifiedOptions) => + resolve([modifiedUrl, modifiedOptions]), + ); } catch (error) { reject(error); } - }); - }); + }, + ); + return await fetch(...modifiedFetchArgs); }; } @@ -1972,7 +1977,7 @@ export type HttpHeaders = {[header: string]: string}; export type FetchMiddleware = ( url: string, options: any, - fetch: Function, + fetch: (modifiedUrl: string, modifiedOptions: any) => void, ) => void; /** diff --git a/web3.js/test/connection.test.ts b/web3.js/test/connection.test.ts index ed52f4accc..958eb298dc 100644 --- a/web3.js/test/connection.test.ts +++ b/web3.js/test/connection.test.ts @@ -133,6 +133,35 @@ describe('Connection', () => { }); } + it('should attribute middleware fatals to the middleware', async () => { + let connection = new Connection(url, { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + fetchMiddleware: (_url, _options, _fetch) => { + throw new Error('This middleware experienced a fatal error'); + }, + }); + const error = await expect(connection.getVersion()).to.be.rejectedWith( + 'This middleware experienced a fatal error', + ); + expect(error) + .to.be.an.instanceOf(Error) + .and.to.have.property('stack') + .that.include('fetchMiddleware'); + }); + + it('should not attribute fetch errors to the middleware', async () => { + let connection = new Connection(url, { + fetchMiddleware: (url, _options, fetch) => { + fetch(url, 'An `Object` was expected here; this is a `TypeError`.'); + }, + }); + const error = await expect(connection.getVersion()).to.be.rejected; + expect(error) + .to.be.an.instanceOf(Error) + .and.to.have.property('stack') + .that.does.not.include('fetchMiddleware'); + }); + it('get account info - not found', async () => { const account = Keypair.generate();