在承诺链中创建错误

问题描述:

如何检查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 
});