获取"at Error (native)"而不是实际的Node.js堆栈跟踪,尽管使用了 err.stack



使用以下示例代码在Windows 10上使用io.js 3.2.0 64bit,并使用node example.js

调用以下代码
'use strict';
const fs = require('fs');
fs.readdir('I_DONT_EXIST', function (/**Error*/ err, /**string[]*/ files) {
    if (err) {
        console.log(err.stack);
    }
});

我得到

{ [Error: ENOENT: no such file or directory, scandir '...I_DONT_EXIST']
  errno: -4058,
  code: 'ENOENT',
  syscall: 'scandir',
  path: '...\I_DONT_EXIST' }
Error: ENOENT: no such file or directory, scandir '...I_DONT_EXIST'
    at Error (native)

所以我得到的是at Error (native)而不是实际的错误跟踪即使我要求的是err.stack

这不应该是实际的堆栈跟踪吗?

编辑:

下面的一小段代码演示了我对下面答案的最后(第三)条注释。

'use strict';
const fs = require('fs');
fs.readdir('I_DONT_EXIST', function (/**Error*/ err, /**string[]*/ files) {
    if (err) {
        console.log('n== 1) Original error');
        console.log(JSON.stringify(err, Reflect.ownKeys(err), 4));
        console.log('n== 2) Original error "stack" property');
        console.log(err.stack);
        const e = new Error(err);
        // Copy parameters I'm interested in from the original object
        e.code = err.code;
        console.log('nn== 3) New error');
        console.log(JSON.stringify(e, Reflect.ownKeys(e), 4));
        console.log('n== 4) New error "stack" property');
        console.log(e.stack);
        console.log('nn== 5) Throw the error');
        throw e;
    }
});

我得到的输出显示,当我检查原始错误对象时,我甚至没有得到错误最终发生的文件位置,但在新对象中得到了一个,这是:

== 1) Original error
{
    "stack": "Error: ENOENT: no such file or directory, scandir 'C:\Users\xxx\I_DONT_EXIST'",
    "message": "ENOENT: no such file or directory, scandir 'C:\Users\xxx\I_DONT_EXIST'",
    "errno": -4058,
    "code": "ENOENT",
    "syscall": "scandir",
    "path": "C:\Users\xxx\I_DONT_EXIST"
}
== 2) Original error "stack" property
Error: ENOENT: no such file or directory, scandir 'C:UsersxxxI_DONT_EXIST'

== 3) New error
{
    "stack": "Error: Error: ENOENT: no such file or directory, scandir 'C:\Users\xxx\I_DONT_EXIST'n    at C:\Users\xxx\test.js:11:19",
    "message": "Error: ENOENT: no such file or directory, scandir 'C:\Users\xxx\I_DONT_EXIST'",
    "code": "ENOENT"
}
== 4) New error "stack" property
Error: Error: ENOENT: no such file or directory, scandir 'C:UsersxxxI_DONT_EXIST'
    at C:Usersxxxtest.js:11:19

== 5) Throw the error
C:Usersxxxtest.js:20
        throw e;
        ^
Error: Error: ENOENT: no such file or directory, scandir 'C:UsersxxxI_DONT_EXIST'
    at C:Usersxxxtest.js:11:19

对于异步方法,通常不会有太多(有用的)堆栈跟踪可用。有像longjohn这样的模块可以帮助为这些方法提供更多的堆栈跟踪,但是您不会希望在生产中使用它,因为它会产生开销。

最新更新