I have a middleware error handler that is working great but next(err) and return and return next(err) seems to not stop execution when dealing with promises. What is the proper way to stop execution of my code when an error is found?
For reference: err is a standard Error class in this case.
I don't think you need the code in userProvider.fetchFriends to help with this but if that's wrong please let me know.
const uid = req.query.steamUserId;
//Use the userProvider to get steam friend data
const friendData = await userProvider.fetchFriends(uid)
.catch(err => {
return next(err); //Does not stop execution. Why? just next(err) doesn't either.
});
//Putting this after every catch works but seems very stupid. How do I avoid this?
if(res.writableEnded)
return;
...Other code that runs but causes errors
}
CodePudding user response:
You've got two problems here.
First: next()
is explicitly continuing to the next middleware or endpoint.
To finish dealing with the request, send a response.
const middleware = (req, res, next) => {
if (something(req)) {
next();
} else {
res.status(500).json({ ok: false, msg: "some error message" });
}
}
Second: You need to watch your asynchronous logic carefully.
You can't:
- trigger something asynchronous
- send a response
- send a different response when the asynchronous function is complete
You can only send one response to a request.
Either:
- Don't call
next
orres.something
in thecatch
block and just log the error internally or - Don't call
next
orres.something
outside the promise handling and move it to athen
handler instead (you might want to switch to usingasync
/await
to make your logic easier to follow)
CodePudding user response:
You can end a response process by using - res.end(), if you need to add status - res.status(404).end().. While next(err) should be used inside the error handler middleware that's while it's not working from where you called it.. read more about error handlers error handling
CodePudding user response:
The issue was that I was mixing async/await with .then/.catch. Needed to use try/catch.
ty @jonsharpe
export const getSteamFriends = async (req, res, next) => {
try{
const uid = req.query.steamUserId;
//Use the userProvider to get steam friend data
const friendData = await userProvider.fetchFriends(uid);
//more code in the middle
} catch(e) {
return next(e);
}
};