From bb5f9a5ab768452de9e166dc28d0ffc234245ef1 Mon Sep 17 00:00:00 2001 From: Dmitriy Mozgovoy Date: Tue, 7 May 2024 21:26:46 +0300 Subject: [PATCH] fix(fetch): treat fetch-related TypeError as an AxiosError.ERR_NETWORK error; (#6380) --- lib/adapters/fetch.js | 13 ++++++++----- test/unit/adapters/fetch.js | 10 ++++++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/lib/adapters/fetch.js b/lib/adapters/fetch.js index c569982..a25b717 100644 --- a/lib/adapters/fetch.js +++ b/lib/adapters/fetch.js @@ -196,13 +196,16 @@ export default isFetchSupported && (async (config) => { } catch (err) { onFinish(); - let {code} = err; - - if (err.name === 'NetworkError') { - code = AxiosError.ERR_NETWORK; + if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) { + throw Object.assign( + new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request), + { + cause: err.cause || err + } + ) } - throw AxiosError.from(err, code, config, request); + throw AxiosError.from(err, err && err.code, config, request); } }); diff --git a/test/unit/adapters/fetch.js b/test/unit/adapters/fetch.js index c47e210..1d8498e 100644 --- a/test/unit/adapters/fetch.js +++ b/test/unit/adapters/fetch.js @@ -370,4 +370,14 @@ describe('supports fetch with nodejs', function () { assert.strictEqual(data, '/?test=1&foo=1&bar=2'); }); + + it('should handle fetch failed error as an AxiosError with ERR_NETWORK code', async () => { + try{ + await fetchAxios('http://notExistsUrl.in.nowhere'); + assert.fail('should fail'); + } catch (err) { + assert.strictEqual(String(err), 'AxiosError: Network Error'); + assert.strictEqual(err.cause && err.cause.code, 'ENOTFOUND'); + } + }); });