0

I can't seem to figure this one out. I have a POST route that is creating a transaction through Stripe using Stripe's Node package.

It works fine until there is an error, say for an example a card with insufficient funds. When the error occurs it calls the catch() block as it should. In the catch block I have return next(err). I am sure to use return because there is other code after the promise that should only run upon success of stripe.charges.create.

However, even with return next(err), it seems as if it continues to run, as illustrated by the console.log I have in place. Additionally, the route returns a 200 status with the "Executed route" text.I also have a global error catcher right after this route. Please feel free to view the images attached below for more detail.

Anyone have any ideas as to why this may be occurring? I've done this structure plenty of times before with no issues; not quite sure what is going on.

Thanks for any input!

The route The global error handler The response

Blake
  • 561
  • 5
  • 14
  • In the future, please post code as text, not as screen shots. Can't search, can't copy paste into answers, harder to read on small screens, higher bandwidth usage, etc... – jfriend00 Feb 04 '19 at 01:17

1 Answers1

1

That's because catch is not in the same scope as the outer code.

You already using async / await here so just use try...catch instead of the callback

try {
  const charge = await stripe.charges.create({
    amount: 100,
    currency: 'usd'
    source: req.body.cardSource
  });
  console.log('Running');
  res.send('Executed route');
} catch (e) {
  return next(e);
}
James
  • 80,725
  • 18
  • 167
  • 237
  • Thanks for this! However, shouldn't the promise catch go to the next middleware with the error provided as well as the return statement regardless? Or am I wrong here? – Blake Feb 03 '19 at 09:28
  • @Blake your promise catch does but it won't stop the rest of the code executing - isn't that what you are trying to avoid here? FWIW the use of `return` is irrelevant in the catch in this example. – James Feb 03 '19 at 09:35
  • Thanks for the response. I'll accept your answer. I also reference this which was helper. Since the catch is past the "point of non-return" https://stackoverflow.com/questions/49417580/express-middleware-cannot-trap-errors-thrown-by-async-await-but-why – Blake Feb 03 '19 at 09:37