Javascript Exception Object Format
Solution 1:
Well, it's not entirely code. It's based on JavaScript's literals syntax, but is just a representation of a the object that's generated from util.inspect()
(or a similar internal function).
The square brackets mention the type of Error
before its message
. And, the rest is a list of enumerable properties and their values that were added to it.
To create it yourself:
var error = new Error("ENOENT, no such file or directory 'InvalidFile'");
error.errno = 34;
error.code = 'ENOENT';
error.path = 'InvalidFile';
error.syscall = 'open'
console.log(error); // uses `util.inspect()`
console.log(util.inspect(error)); // or use it directly
console.log(error.message); // "ENOENT, no such ..."
console.log(Object.prototype.toString.call(error)); // "[object Error]"
And, for a larger sample of the format, try logging some built in modules:
console.log(console);
{ log: [Function],
info: [Function],
warn: [Function],
error: [Function],
dir: [Function],
time: [Function],
timeEnd: [Function],
trace: [Function],
assert: [Function],
Console: [Function:Console] }
Solution 2:
I'm answering subquestion #2. The accepted answer, though excellent, seems to omit it.
On Node, the [Error: ...] element can be accessed as .stack on the exception object. It's a string, which you can then parse with regular expressions to get, for instance, the module and line number.
For instance, you could parse the first stack frame like this:
...
} catch (e) {
var msg, file, line, col;
[msg,file,col] = e.stack.match(/\((.*):(\d+)\)/);
if (file) {
[,file,line] = file.match(/(.*):(\d+)/);
}
}
Post a Comment for "Javascript Exception Object Format"