ccnokes ccnokes - 3 months ago 12
Node.js Question

Q Reject promise within .then success callback

I'm using kriskowal Q promise library in a node app.
I have code that reads a file and then attempts to parse part of it into a Javascript Date object (I have similar code in other places that attempts to do a JSON.parse). In these circumstances I've read and personally feel it's best practice to wrap that code in a try/catch block to avoid and potentially fatal surprises. Here's some real code mixed with psuedo code:

var getMonitorTimestamp = function() {
return readLogFile()
.then(
function ok(contents) {
//regex to capture dates in format of: 09 Jan 2015 09:42:01
var regex = /[0-9]{2} [\w]{3} [0-9]{4} ([0-9]{2}:){2}[0-9]{2}/g;
var timestamp = contents.match(regex)[0];
var date;
try {
date = new Date(timestamp);
return date;
}
//when I've caught the error here, how do I reject the promise?
//this will still return an error to the next success callback in the queue
catch(e) {
console.error(e);
return e;
}

},
function err(e) {
console.error(e);
return new Error();
}
);
};


exports.sendRes = function(req, res) {
getMonitorTimestamp()
.then(
function yay(data) {
//don't want to send an error here
res.json({result: data});
},
function boo(e) {
res.status(500).json({error: e});
}
);
}


As you can see, it would be useful to reject the promise in the getMonitorTimstamp->ok callback because it failed.

Is there a way to do that in Q? I haven't found anything (yet). Or is there a different pattern for handling this scenario?

Answer

This is actually covered in the q docs under the section Handling Errors.

Instead of using the .then(success, fail) style, you'll want to chain your handlers to allow the success handler to throw to the fail handler.

readLogFile()
  .then(function yay(data) {
    throw "Eek!";
  })
  .fail(function boo(e) {
    res.status(500).json({error: e});
  });
Comments