在承诺链中创建错误

Creating an error in promise chain

本文关键字:创建 错误 承诺      更新时间:2023-09-26

我将如何检查属性的 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);
});

示例取自蓝鸟文档。

您可以使用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
});