javascript exception object format

exception, javascript, node.js, object

Solution

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] }

Problem

By default, Node.js throws the following exception when a file is not found. ``` { [Error: ENOENT, no such file or directory 'InvalidFile'] errno: 34, code: 'ENOENT', path: 'InvalidFile', syscall: 'open' } ``` Technically speaking, this is supposed to be a JavaScript Object. As per the javascript object sematics, there should be a comma to separate member elements. In this case, there is no comma between `[Error: ENOENT, no such file or directory 'InvalidFile']` and `errno: 34,`. My questions are How do I construct an object like this? How do I access the `[Error: ENOENT, no such file or directory 'InvalidFile']` element in a program?

Original source