2014-12-04 43 views
1

如何檢查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的示例。

回答

1

,你可以利用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 
});