javascript exception object format

后端 未结 2 918
心在旅途
心在旅途 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+)/);
        }
    }
    

提交回复
热议问题