I find lots of posts that almost answer the question, but nothing quite works for me.
I have an async function:
const doStuff = async (data)=>{
if(data == "a bug")
throw(new Error('Error! Bug found'));
return "not a bug";
}
I call the function on a route handler:
app.get('/doStuffRoute', async (req, res, next)=>{
const result = await doStuff("a bug")
.catch((err)=>{return next(err);});
console.log("This shouldn't execute!");
}
The error gets handled just fine by my custom error middleware, prints out the error, etc. But then I still see This shouldn't execute!
being printed as well!
From all my research and reading, await X.catch(error)
should be identical to try{ await X } catch {error}
. And I really prefer .catch();
if at all possible. There are dozens and dozens of tutorials showing this, and even a few stackoverflow posts explicitly stating this to be the case. However I also occasionally find a post cryptically saying "don't use await with .catch()" with no other explanation or detail, so I don't know what to think.
The only hint I can find is adding return
before your next(err)
call should be enough to halt execution, but it doesn't seem to actually work if return next(err);
is inside a .catch()
block.
What is going on? Are my sources lying? Am I misunderstanding some basic fundamental concept? I appreciate any help getting me on track.
As a bonus question, why do so many people suggest a wrapper function a-la express-async-handler? Why would this have any different behavior than just calling the async function directly and handling it?