如何检查 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/