我将如何检查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文档。
您可以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
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句