javascript exception object format

后端 未结 2 919
心在旅途
心在旅途 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:24

    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+)/);
        }
    }
    
    0 讨论(0)
  • 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] }
    
    0 讨论(0)
提交回复
热议问题