在 Windows 10 上的 io.js 3.2.0 64 位中使用以下示例代码,并使用 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
。
这不应该是实际的堆栈跟踪吗?
编辑:
这是一小段代码,展示了我对以下答案的最后(第 3 次)评论。
'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('\n\n== 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('\n\n== 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:\Users\xxx\I_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:\Users\xxx\I_DONT_EXIST'
at C:\Users\xxx\test.js:11:19
== 5) Throw the error
C:\Users\xxx\test.js:20
throw e;
^
Error: Error: ENOENT: no such file or directory, scandir 'C:\Users\xxx\I_DONT_EXIST'
at C:\Users\xxx\test.js:11:19
最佳答案
通常对于异步方法,不会有太多(有用的)堆栈跟踪可用。有类似 longjohn
的模块这有助于为此类方法提供更多的堆栈跟踪,但您不希望在生产中使用它,因为它会产生开销。
关于node.js - 尽管使用 err.stack,但获取 "at Error (native)"而不是实际的 node.js 堆栈跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32235848/