如何告诉回调中错误的真实来源



这可能是非常基本的,但我是JavaScript的新手,显然不知道它的正确搜索词。

我试图在多个地方使用一个函数作为回调。然而,我不知道如何让回调函数告诉我错误的真正来源。

// `throwIfError` is a function that could be used as a callback
// in multiple places.
function throwIfError(err) {
if(err) {
// Some code that will tell me that the error originated from a call
// to `fs.writeFile` in this file (that is, line 13), instead of
// from the internals of the `writeFile` function. After that, it
// will throw the same or a new error so that the program will fail
// early, instead of continuing with the wrong data.
}
}
require('fs').writeFile(
'some_non_existent_directory/test.txt',
'',
throwIfError
);

使用额外的参数调用回调。

function throwIfError(err, fromwhere) {
if(err) {
console.log(`Error came from ${fromwhere}`);
}
}
require('fs').writeFile(
'some_non_existent_directory/test.txt',
'',
err => throwIfError(err, 'fs.writeFile')
);

相关内容

最新更新