在io中使用以下示例代码。js 3.2.0 64位,并使用
node example.js
'use strict';
const fs = require('fs');
fs.readdir('I_DONT_EXIST', function ( err, 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 ( err, 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);
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