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)
?