简体   繁体   中英

Bluebird promises on Node.js: error and exception handling

I use bluebird promises for a node.js application (MEAN environment). I am having trouble understanding exception/error handling though. Consider the following code:

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 - promisified:

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

I got two questions now.

  1. What do I have to return from library1 to get its promise rejected? If not by returning a value, how can I do that?
  2. How do I define and catch my own exceptions? The code above results in this error:

     Unhandled rejection ReferenceError: LinkError/SizeError is not defined 

.promisify*() turns the regular Node.js callback convention into promises. Part of that convention is that errors are passed as first argument to a callback function.

In other words, to reject the promise, use cb(new Error(...)) .

Example:

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);
});

As for the missing error types: I assume that they are exported by secondlibrary so use library2.LinkError instead of just LinkError . If they aren't exported you cannot catch them explicitly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM