Skip to content

Commit 92e38fc

Browse files
authored
fix: handle undefined __filename in bundled environments (#4812)
1 parent 283f2aa commit 92e38fc

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

index-fetch.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ const { getGlobalDispatcher, setGlobalDispatcher } = require('./lib/global')
44
const EnvHttpProxyAgent = require('./lib/dispatcher/env-http-proxy-agent')
55
const fetchImpl = require('./lib/web/fetch').fetch
66

7+
// Capture __filename at module load time for stack trace augmentation.
8+
// This may be undefined when bundled in environments like Node.js internals.
9+
const currentFilename = typeof __filename !== 'undefined' ? __filename : undefined
10+
711
function appendFetchStackTrace (err, filename) {
812
if (!err || typeof err !== 'object') {
913
return
@@ -30,7 +34,11 @@ function appendFetchStackTrace (err, filename) {
3034

3135
module.exports.fetch = function fetch (init, options = undefined) {
3236
return fetchImpl(init, options).catch(err => {
33-
appendFetchStackTrace(err, __filename)
37+
if (currentFilename) {
38+
appendFetchStackTrace(err, currentFilename)
39+
} else if (err && typeof err === 'object') {
40+
Error.captureStackTrace(err, module.exports.fetch)
41+
}
3442
throw err
3543
})
3644
}

index.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,10 @@ module.exports.getGlobalDispatcher = getGlobalDispatcher
121121

122122
const fetchImpl = require('./lib/web/fetch').fetch
123123

124+
// Capture __filename at module load time for stack trace augmentation.
125+
// This may be undefined when bundled in environments like Node.js internals.
126+
const currentFilename = typeof __filename !== 'undefined' ? __filename : undefined
127+
124128
function appendFetchStackTrace (err, filename) {
125129
if (!err || typeof err !== 'object') {
126130
return
@@ -147,7 +151,11 @@ function appendFetchStackTrace (err, filename) {
147151

148152
module.exports.fetch = function fetch (init, options = undefined) {
149153
return fetchImpl(init, options).catch(err => {
150-
appendFetchStackTrace(err, __filename)
154+
if (currentFilename) {
155+
appendFetchStackTrace(err, currentFilename)
156+
} else if (err && typeof err === 'object') {
157+
Error.captureStackTrace(err, module.exports.fetch)
158+
}
151159
throw err
152160
})
153161
}

0 commit comments

Comments
 (0)