fix: Improve get caller file path util (#7974)
* fix: Improve get caller file path util * improve compatibility * update comment --------- Co-authored-by: Riqwan Thamir <rmthamir@gmail.com>
This commit is contained in:
co-authored by
Riqwan Thamir
parent
de0a9c14ab
commit
1393f51046
@@ -4,24 +4,26 @@
|
||||
*/
|
||||
export function getCallerFilePath(position = 2) {
|
||||
if (position >= Error.stackTraceLimit) {
|
||||
throw new TypeError(
|
||||
"getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `" +
|
||||
position +
|
||||
"` and Error.stackTraceLimit was: `" +
|
||||
Error.stackTraceLimit +
|
||||
"`"
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
const oldPrepareStackTrace = Error.prepareStackTrace
|
||||
Error.prepareStackTrace = (_, stack) => stack
|
||||
const stack = new Error().stack
|
||||
|
||||
let result!: string
|
||||
|
||||
Error.prepareStackTrace = (_, stack) => {
|
||||
if (stack !== null && typeof stack === "object") {
|
||||
// stack[0] holds this file
|
||||
// stack[1] holds where this function was called
|
||||
// stack[2] holds the file we're interested in, in most cases, otherwise we need to get higher
|
||||
result = stack[position]
|
||||
? (stack[position] as any).getFileName()
|
||||
: undefined
|
||||
}
|
||||
return stack
|
||||
}
|
||||
new Error().stack
|
||||
Error.prepareStackTrace = oldPrepareStackTrace
|
||||
|
||||
if (stack !== null && typeof stack === "object") {
|
||||
// stack[0] holds this file
|
||||
// stack[1] holds where this function was called
|
||||
// stack[2] holds the file we're interested in
|
||||
return stack[position] ? (stack[position] as any).getFileName() : undefined
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user