Siddharth Srivastva Siddharth Srivastva - 1 month ago 8
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.
Normally:

First.Ctrl

var second_ctrl = require( '../ctrl/second');
testCode : function(req, res, next){
return second_ctrl.getData()
.then(function(resultData){
res.json(resultData);
})
.catch(function(error){
res.json(error)
})
}


Second.Ctrl

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()
.then(function(result){
if(result == null)
throw new Error ('No data found');
return result;
})
.catch(function(error){
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

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.