Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在承诺链中创建错误_Javascript_Node.js_Promise_Bluebird - Fatal编程技术网

Javascript 在承诺链中创建错误

Javascript 在承诺链中创建错误,javascript,node.js,promise,bluebird,Javascript,Node.js,Promise,Bluebird,如何检查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"); retu

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

示例取自。

您可以像其他错误一样使用操作数的
类型、catch undefined和throw/catch,具体来说,您可以在您的情况下使用
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
});