-
-
Save mmalecki/3000364 to your computer and use it in GitHub Desktop.
function getLine(offset) { | |
var stack = new Error().stack.split('\n'), | |
line = stack[(offset || 1) + 1].split(':'); | |
return parseInt(line[line.length - 2], 10); | |
} | |
global.__defineGetter__('__LINE__', function () { | |
return getLine(2); | |
}); | |
console.log(__LINE__); | |
console.log(getLine()); |
Modified this to
function getLine (err) {
let stack = err.stack.split('\n')
let line = stack[1 + 1].split(':')
return parseInt(line[line.length - 2], 10)
}
And now I can pass in an error object after catching it and before re-throwing to preserve the line where it occurred, where I would normally get the line that I re-throw the error at in Node.JS. A bit more complex than the below, but this seems like a good example:
let val
try {
Object.assign(val, 1)
} catch (err) {
let reason = `${err.message.toLowerCase()} ("${err.code || err.name || 'error'}" @ line ${getLine(err)})`
throw new Error(`Failed to do something because: ${reason}.`)
}
Of course this requires looking at the error message, but that's what logging is for, and I think it will make [my] life a little easier by helping to find some bugs that get past the standard-js linter like the above example.
Thank you :D
Edits: eventually fixed formatting. I really hate MD sometimes. https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet helped.
Another edit: That's also without assigning it to global or window; just using it as a private function in a module without that part.
It finally worked for me like this (using Chrome 45 under Windows 7):