0

I'm creating a backend REST Api server in Node.js using express and I'm trying to understand what the "correct" way of telling the client that an error has occurred and to not continue on with the middlewares

In my current code...

If I have the route router.post('/test', [first, second]);

If there is no error, I do return next() in first to run the second function and then return res.sendStatus(200) in second

This is correct, right?

But now let's say an error occurs in first does it make sense to do return res.sendStatus(500) or return next(new Error('Error has occurred'))

Or should I do

res.sendStatus(500)
return next(new Error('error occurred'))

Or is there a way to just send the statusCode inside of return next(error)

My understanding is that using a return stops the continuation of the middlewares anyway, so I'm not sure how to do this?

Should I only use next() to continue and never use next(error) ?

LongTSQLFiles
  • 183
  • 2
  • 11
  • Does this answer your question? [Express next function, what is it really for?](https://stackoverflow.com/questions/13133071/express-next-function-what-is-it-really-for) – Dan O Apr 14 '20 at 04:28
  • @DanO Not quite. I do understand that next is for continuing onto the chain of middlewares. I guess I just don't understand the best way to stop and send a statuscode to the client – LongTSQLFiles Apr 14 '20 at 04:31

0 Answers0