Siddharth Srivastva Siddharth Srivastva - 1 year ago 54
Node.js Question

Returning errors in nested then and promises ExpressJS/NodeJs

I am having a bit of confusion on returning error from function calls.
For example purpose, I am using sequelizeJS to illustrate the point.


var second_ctrl = require( '../ctrl/second');
testCode : function(req, res, next){
return second_ctrl.getData()


getData : function(){
return models.Data.findAll()

Any error in the getData findAll would go to catch block of first_ctrl. But if I have to do some manipulations like:

Second.Ctrl - Manipulation

getData : function(){
return models.Data.findAll()
if(result == null)
throw new Error ('No data found');
return result;
throw error;
//return error

I have tried using throw error, return error and removing the inner catch block but in both cases - the execution goes to then block in first_ctrl with resultData having received the error object.

What is the best practice for this kind of situations as these nested call can go even deeper (first_ctrl -> second_ctrl -> third_ctrl)

Let me know. Looking forward to your thoughts

Answer Source

Not a complete answer yet but it hopefully helps you to get on track.

Your core idea is right. Following code works:

const myPromise = Promise.reject(new Error('some error'))
  .then(res => console.log('inner then'))
  .catch(err => {
    console.log('inner err');
    throw err
  .then(res => console.log('outer then'))
  .catch(err => console.log('outer err'));
// logs:
//   inner err
//   outer err

So following things i can imagine are possible the cause of our problem:

  • you are in the outer catch block without noticing it (you call res.json() in there as well as in your outer then - how do you know which one is getting called)
  • you are using a bugged promise library.

Hope this helps at least a bit.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download