javascript - 在 promise 链中创建错误

标签 javascript node.js promise bluebird

如何检查 JSON 中的属性,如果缺少,则返回退出并捕获链的错误?

var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs"));

fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) {
    if (!json.prop) return new Error("missing prop");
    return json;
}).catch(SyntaxError, function (e) {
    console.error("file contains invalid json");
}).catch(Promise.OperationalError, function (e) {
    console.error("unable to read file, because: ", e.message);
});

示例取自 bluebird documentation .

最佳答案

您可以使用 typeof 操作数,捕获未定义并像其他错误一样抛出/捕获,特别是您可以在您的情况下使用 ReferenceError 类型:

fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) {
    if (typeof json.prop === "undefined") throw new ReferenceError("missing prop");
    return json;
}).catch(SyntaxError, function (e) {
    console.error("file contains invalid json");
}).catch(Promise.OperationalError, function (e) {
    console.error("unable to read file, because: ", e.message);
}).catch(ReferenceError,function(e){
    //handle the error
});

关于javascript - 在 promise 链中创建错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27301910/

相关文章:

javascript - 无法通过 for 循环传递动态 div id

Node.js process.stdout.write 在 for 循环中闪烁

javascript - 调用 Firebase Cloud Messaging sendToDevice 时程序不会退出

node.js - Q.js 变量在并行流中传递

javascript - Bootstrap multiselect - 在单击取消选择/取消选中所有选项时触发事件 'onSelectAll' 或 'onDeselectAll'(需要的最佳方式)

javascript - 我无法从 JSON 文件获取数据 - $.getJSON 不起作用

javascript - 在浏览器中使用 JavaScript 读取带有 for-await 的流

javascript - 如何将字符集添加到 Knex.js 连接字符串?

node.js - 监控 Node.js 中的启动/运行/结束应用程序

javascript - 带提示的 Puppeteer,忽略其余功能