javascript exception object format

后端 未结 2 921
心在旅途
心在旅途 2021-01-22 06:36

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: \'         


        
2条回答
  •  春和景丽
    2021-01-22 07:33

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

提交回复
热议问题