在承诺链中创建错误
Creating an error in promise chain
我将如何检查属性的 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);
});
示例取自蓝鸟文档。
您可以使用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
});
相关文章:
- 错误:自动化服务器可以't创建对象
- 服务器端帐户创建错误
- 创建到电子表格创建错误中的文件的链接的脚本“;无法转换“”;
- JavaScript 新日期创建错误
- 在承诺链中创建错误
- 在 jQuery 中创建错误处理
- Javascript 文件变量声明/创建错误:此对象不支持此操作
- 在角度后期创建错误的对象
- jquery元素创建错误
- 简单的javascript游戏:由于构造函数或条件操作符导致的对象创建错误
- 创建错误消息
- Javascript 动态表创建错误
- 日期.UTC创建错误的日期
- Javascript regexp创建错误
- 我一直得到对象.在IE8中创建错误
- 在else语句中创建错误
- 完美的JavaScript语法在Eval()中创建错误
- openDatabase在Android PhoneGap应用程序中创建错误
- 在 C# 中创建错误
- 使用Django/Javascript创建错误信息