Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save isocroft/a42a5a1ce887b2084679adcf86bf907f to your computer and use it in GitHub Desktop.
Save isocroft/a42a5a1ce887b2084679adcf86bf907f to your computer and use it in GitHub Desktop.
This is a polyfill that makes it possible to replicate the Firefox properties for browser errors to get the 'fileName', 'columnNumber' and 'lineNumber'
if (typeof InstallTrigger === "undefined") { // If the browser isn't a Gecko-based browser (e.g. Firefox)
Object.defineProperty(Error.prototype, 'columnNumber', {
configurable: false,
enumerable: false,
get: function () {
const stackString = (this.stack || '').toString();
const regexStackFrameLine = /at (?:(?:[\w ])+) \(([^:]+)\:([\d]+)\:([\d]+)\)\s*/g
const [ _, fileName, lineNumber, columnNumber ] = regexStackFrameLine.exec(stackString) || [ '', '<anonymous>', '1', '1' ]
return (typeof(chrome) !== 'undefined' || typeof(msCrypto) !== 'undefined' || typeof(process) !== 'undefined') ? columnNumber : 0;
}
});
Object.defineProperty(Error.prototype, 'lineNumber', {
configurable: false,
enumerable: false,
get: function () {
const stackString = (this.stack || '').toString();
const regexStackFrameLine = /at (?:(?:[\w ])+) \(([^:]+)\:([\d]+)\:([\d]+)\)\s*/g
const [ _, fileName, lineNumber, columnNumber ] = regexStackFrameLine.exec(stackString) || [ '', '<anonymous>', '1', '1' ]
return (typeof(chrome) !== 'undefined' || typeof(msCrypto) !== 'undefined' || typeof(process) !== 'undefined') ? lineNumber : this.line.number;
}
});
Object.defineProperty(Error.prototype, 'fileName', {
configurable: false,
enumerable: false,
get: function () {
const stackString = (this.stack || '').toString();
const regexStackFrameLine = /at (?:(?:[\w ])+) \(([^:]+)\:([\d]+)\:([\d]+)\)\s*/g
const [ _, fileName, lineNumber, columnNumber ] = regexStackFrameLine.exec(stackString) || [ '', '<anonymous>', '1', '1' ]
return (typeof(chrome) !== 'undefined' || typeof(msCrypto) !== 'undefined' || typeof(process) !== 'undefined') ? fileName : this.sourceURL;
}
});
}
@alphakmfb
Copy link

alphakmfb commented Mar 31, 2021

Oh so you can use it like so ? Cool 💯 🥇

try {
  tryToCallAnUndefinedFunction()
} catch (e) {
  // This line below will now work on both Firefox and Chrome (not only Firefox)
  console.log(e.name, e.message, e.fileName, e.columnNumber, e.lineNumber)
}

I feel this can also be used for V8. Like NodeJS right ?

@isocroft
Copy link
Author

isocroft commented Apr 1, 2021

Yeah, that's right @alphakmfb. It also works in Internet Explorer 11 and Edge 12+

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment