Last active
August 25, 2015 19:49
-
-
Save Qix-/55291ff9626c0398ab00 to your computer and use it in GitHub Desktop.
Error hacking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function applyFilename(err) { | |
var descriptor = Object.getOwnPropertyDescriptor(err, 'stack'); | |
var getter = descriptor.get; | |
descriptor.get = function () { | |
var lines = getter.call(this).split(/[\r\n]+/g); | |
if (this.fileName) { | |
lines[0] += ' in ' + this.fileName; | |
} | |
return lines.join('\n'); | |
}; | |
Object.defineProperty(err, 'stack', descriptor); | |
return err; | |
} | |
try { | |
try { | |
throw new applyFilename(new Error('bad JSON')); | |
} catch (e) { | |
e.message = 'really, really, really bad JSON'; | |
e.fileName = '/a/b/c/d/bad-json.json'; | |
throw e; | |
} | |
} catch (e) { | |
console.error(e.stack); | |
} | |
try { | |
try { | |
throw new applyFilename(new Error('bad JSON')); | |
} catch (e) { | |
e.message = 'unknown filename'; | |
throw e; | |
} | |
} catch (e) { | |
console.error(e.stack); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ node test | |
Error: really, really, really bad JSON in /a/b/c/d/bad-json.json | |
at Object.<anonymous> (/private/tmp/pkg/test.js:17:29) | |
at Module._compile (module.js:460:26) | |
at Object.Module._extensions..js (module.js:478:10) | |
at Module.load (module.js:355:32) | |
at Function.Module._load (module.js:310:12) | |
at Function.Module.runMain (module.js:501:10) | |
at startup (node.js:129:16) | |
at node.js:814:3 | |
Error: unknown filename | |
at Object.<anonymous> (/private/tmp/pkg/test.js:29:29) | |
at Module._compile (module.js:460:26) | |
at Object.Module._extensions..js (module.js:478:10) | |
at Module.load (module.js:355:32) | |
at Function.Module._load (module.js:310:12) | |
at Function.Module.runMain (module.js:501:10) | |
at startup (node.js:129:16) | |
at node.js:814:3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Almost, I would like to have the
.fileName
added to the err.message.Basically, I want:
To become this when
.fileName
is set: