简体   繁体   中英

Handle error in promise ES6 nodejs

Hi I am new to ES6 and I am using promise chain

I am not getting error catch in my promise chain.

let cost, stars;
getStarInfo(req.body.star_id).then( (star) => {

   let stripe_object = new Stripe(req.body.stripe_token, cost);
   return stripe_object.makepayment(); 
}).then( (payment) => {
    console.log(1 ,payment);
    return savePurchase(req.decoded._id, cost, stars, payment.id);
}).catch( (err) => {

    res.json({'success' : false , 'err' : err ,  msg : 'Something went wrong please try again'});        
});

My savePurchase function is like this

function savePurchase( cost , stars, payment_id){


    console.log("hello")
    return new Promise( (resolve, reject) => {

        var purchasedstars = new Stars({

            user_id      : user_id,
            stars        : stars,
            money_earned : cost,
            transaction_id : payment_id
        });  
        console.log(purchasedstars)

        purchasedstars.save(function(err , saved_doc){
            console.log('save' , err , saved_doc)
            if(err){

                reject(err)
            }else{

                resolve(saved_doc);
            }
        });
    });
}

In savePurchase function if my user_id is undefined, the promise does not give me error. It just goes in the catch and give empty error object. How can I find out the error in my function.?

savePurchase返回一个新的savePurchase您将其链式catch与之链接,但不再与getStarInfo savePurchase链接,因此您没有getStarInfo错误处理程序。

.then() takes an optional second function to handle errors

var p1 = new Promise( (resolve, reject) => {
  resolve('Success!');
  // or
  // reject ("Error!");
} );

p1.then( value => {
  console.log(value); // Success!
}, reason => {
  console.log(reason); // Error!
} );

Define custom error and reject.

purchasedstars.save(function (err, saved_doc) {
    console.log('save', err, saved_doc)
    if (err) {
        reject({
            err,
            message: 'Some error message'
        })
    } else {
        resolve(saved_doc);
    }
});

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