javascript - Bluebird 在 Node.js 上 promise : error and exception handling

标签 javascript node.js promise bluebird

我将 bluebird Promise 用于 Node.js 应用程序(MEAN 环境)。不过,我无法理解异常/错误处理。考虑以下代码:

var Promise = require('bluebird'),
    library1 = Promise.promisifyAll(require('firstlibrary')),
    library2 = Promise.promisifyAll(require('secondlibrary'));

//main
exports.urlchecker = function(req, res) {
    library1.doSomething(req.body.url) //--> how to reject this promise?
        .then(function(response) {
            if (response == false) {
                throw new LinkError("URL invalid!");
            }

            library2.Foo(req.body.url)
                .then(function(response2) {
                    if (response2 == false) {
                        throw new SizeError("URL too long!");
                    }
                    res.json({
                        status: true
                    });
                }).catch(LinkError, function(e) { //--> causes error!
                    res.json({
                        status: false
                    });
                }).catch(SizeError, function(e) { //--> causes error!
                    res.json({
                        status: false
                    });
                }).catch(function(e) { //--> catch all other exceptions!
                    res.json({
                        status: false
                    });
                });
        });
};

library1 - promise :

exports.doSomething = function(url, cb) {
    if (whatever == 0) {
        cb(null, false); //--> what to return to reject promise?
    } else {
        cb(null, true);
    }
};

我现在有两个问题。

  1. 我必须从 library1 返回什么才能使其 Promise 被拒绝?如果不返回值,我该怎么做?
  2. 如何定义和捕获自己的异常?上面的代码会导致此错误:

    Unhandled rejection ReferenceError: LinkError/SizeError is not defined
    

最佳答案

.promisify*() 将常规 Node.js 回调约定转换为 Promise。该约定的一部分是错误作为第一个参数传递给回调函数。

换句话说,要拒绝 promise ,请使用cb(new Error(...))

示例:

var Promise = require('bluebird');

var library1 = {
  // If `doFail` is true, "return" an error.
  doSomething : function(doFail, cb) {
    if (doFail) {
      return cb(new Error('I failed'));
    } else {
      return cb(null, 'hello world');
    }
  }
};

var doSomething = Promise.promisify(library1.doSomething);

// Call that resolves.
doSomething(false).then(function(result) {
  console.log('result:', result);
}).catch(function(err) {
  console.log('error:', err);
});

// Call that rejects.
doSomething(true).then(function(result) {
  console.log('result:', result);
}).catch(function(err) {
  console.log('error:', err);
});

至于缺少的错误类型:我假设它们是由 secondlibrary 导出的,因此使用 library2.LinkError 而不是仅 LinkError。如果它们没有导出,您就无法明确地捕获它们。

关于javascript - Bluebird 在 Node.js 上 promise : error and exception handling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30841553/

相关文章:

按类型分类的 Javascript/JQuery 参数

node.js - GraphQL 嵌套解析器

callback - 外来控制流的 ES6 Promise 模式

javascript - Grunt——在同一端口上运行 Connect 和 Express 服务器

javascript - TypeScript 中的 friend 类

javascript - Kendo grid - 如何使用 JavaScript 打开弹出编辑窗口

node.js - 如何在 express - node js 中使用集群的粘性 session

node.js - 如何使用 Express/Node.JS 通过 EJS 渲染 Markdown?

javascript - promise 何时被摧毁?

javascript - Q promises - 数组中每个元素的 Node.js 函数