'reliable way to get line / column number from javascript Error?
I have a little embedded JS editor on my site and when the code inside it throws an error I'd like to underline where the error is happening. The error stack trace looks like this:
err ReferenceError: a is not defined
at isNumber (eval at handle_message (about:srcdoc:11:7), <anonymous>:5:5)
at Array.filter (<anonymous>)
at removeNumbers (eval at handle_message (about:srcdoc:11:7), <anonymous>:13:15)
at eval (eval at handle_message (about:srcdoc:11:7), <anonymous>:16:28)
at handle_message (about:srcdoc:14:7)
In this case my desired solution would return { line: 5, column: 5 } (the first entry of the stack trace)
My first instinct is just to do some text parsing + regex to get the last 2 numbers from the second line. This seems like a super unreliable solution though, and I'm not sure if stack traces will follow this format for all types of errors and on all browsers.
Is there a more reliable way to extract the error location from a javascript Error object?
Solution 1:[1]
There is a built-in way to get the line and column number in JavaScript, but unfortunately, it isn't supported in (literally) all browsers. The only browser that supports it is Firefox.
Right now, the best thing you can do is just get it from the browser console.
However, to get it from the Error object, you can first wrap your code in a try/catch statement.
try {
a();
} catch (err) {
console.log(err); // ReferenceError: a is...
}
Then, you can get the line and column numbers from it. Beware; it's only supported in Mozilla!
console.log(err.lineNumber, err.columnNumber); // 5 5
The only properties that aren't non-standard in the Error object is the name and message.
In conclusion, even though there is a built-in way to get the line and column number in JavaScript, it is non-standard and only supported in Firefox.
The best way to get it is to get it from the browser console (or to get it from third-party libraries, if possible).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arnav Thorat |
