Skip to content

Instantly share code, notes, and snippets.

@Qix-
Last active August 25, 2015 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Qix-/55291ff9626c0398ab00 to your computer and use it in GitHub Desktop.
Save Qix-/55291ff9626c0398ab00 to your computer and use it in GitHub Desktop.
Error hacking
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);
}
$ 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
@sindresorhus
Copy link

Almost, I would like to have the .fileName added to the err.message.

Basically, I want:

SyntaxError: Trailing comma in object at 3:1
}
^

To become this when .fileName is set:

SyntaxError: Trailing comma in object at 3:1 in /a/b/c/d/bad-json.json
}
^

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