0

Here is My code,i just started learning Promises, trying to Handle the error using promise Catch blocks, is there any way to handle both errors using only one catch block, in my code i am using two catch blocks to handle the errors. can any bdy help me on this.

 exports.create = function (req, res) {
        DetailsValidator.validator.keyValidator(req.body).then(success=>{
            return true
        }).then((result)=>{
            console.log("coming Body is", req.body);
            let acount = new CloudAccountDetailSchema();
            acount.type = 1;// For Aws its type is one
            acount.owner = 212;
            acount.projectId = req.query.pId;
            acount.save().then(accountDetail=> {
                res.status(201).json({
                    success: true,
                    data: {
                        message: " account successfully added"
                    }
                })
            }).catch((e)=>{
                return res.status(409).send({
                    success: false,
                    message: e
                });
            })
        }).catch(err => {
            return res.status(409).send({
                success: false,
                message: err
            });
        })

    };
Jeevan
  • 756
  • 13
  • 39
  • Possible duplicate of [Handling multiple catches in promise chain](http://stackoverflow.com/questions/26076511/handling-multiple-catches-in-promise-chain) – Supradeep Jan 08 '17 at 06:55

2 Answers2

2

You can flatten your Promise chain and have everything propagate to a final catch block. Remember that you can return a promise in a .then(...) callback and convert your promise state to that new promise's state:

exports.create = function (req, res) {
  DetailsValidator.validator.keyValidator(req.body).then(success=>{
    return true
  }).then((result)=>{
    console.log("coming Body is", req.body);
    let acount = new CloudAccountDetailSchema();
    acount.type = 1;// For Aws its type is one
    acount.owner = 212;
    acount.projectId = req.query.pId;
    return acount.save();
  }).then(accountDetail=> {
    res.status(201).json({
      success: true,
      data: {
        message: " account successfully added"
      }
    });
  }).catch(err => {
    return res.status(409).send({
      success: false,
      message: err
    });
  });
}
Jacob
  • 77,566
  • 24
  • 149
  • 228
0

You could use libraries like BlueBird or Q that has the catch already implemented, but you could do it easily with async/await like this:

async function someFunction(){
  try{ 
   const firstPromise = await someAsyncFunction()
   const secondPromise = await $.ajax({ ... })
   console.log(firstPromise)
   return secondPromise
  }catch(e){
    console.log('Catch any error in the block only once')
  }
}
damianfabian
  • 1,681
  • 12
  • 16