我使用以下代码
require('./ut/valid').validateFile()
});
在验证文件中,当我发现配置中有一些重复项时,我发送错误 就像下面的
module.exports = {
validateFile: function (req) {
...
if(dup){
console.log("Duplicate found: ");
return new Error("Duplicate found: ");
}
dup 为 true 并且应该抛出错误,我应该如何在异步方法中“捕获”它?
我也尝试过如下
require('./ut/valid').validateFile(function() {
process.exit(1);
});
我在这里想念的是,我能够看到控制台日志......
最佳答案
您的方法不起作用,因为您正在执行异步操作。常见的解决方案是使用回调。在 Node.js 中,通常使用名为 error first callbacks 的模式。 .
这意味着您需要将回调
函数传递给您的文件验证方法,并返回错误或您的文件:
// './utils/validate.js'
module.exports = {
/**
* Validates a file.
*
* @param {Function} next - callback function that either exposes an error or the file in question
*/
file: function (next) {
// ...
if (duplicate) {
console.log('Duplicate found!');
var error = new Error('Duplicate File');
// Perhaps enrich the error Object.
return next(error);
}
// Eveything is ok, return the file.
next(null, file);
}
};
你可以像这样使用它:
// './app.js'
var validate = require('./utils/validate');
validate.file(function (err, file) {
if (err) {
// Handle error.
process.exit(1);
}
// Everything is ok, use the file.
console.log('file: ', file);
});
关于javascript - Node 中的异步方法没有收到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31724203/