You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Express 4.x doesn't quite do async properly, in that you have to manually deal with the error case and call next(err) manually so that errors propagate down the middleware chain to the eventual default error handler.
The trick is to turn code like this:
router.get('/:id',async(req,res)=>{const{ id }=req.params;constdata=awaitgetSomething(id);res.json(data);});
into something like this:
router.get('/:id',async(req,res,next)=>{try{const{ id }=req.params;constdata=awaitgetSomething(id);res.json(data);}catch(err){next(err);}});
Basically, we have to either deal with the error case in the route (i.e., don't let it go further in any code path), or call next(err) ourselves when things blow up. I haven't looked at all of our routes to see if they need changing, so this is a bug to audit things.
The text was updated successfully, but these errors were encountered:
In the code you listed above, we aren't using async, so this doesn't apply. However, in this case we do need to do something different from the usual error handler: we want to redirect.
One thing I noticed in all the asynchronous function callbacks is that many of them do not call next(err). Is this something that needs to be fixed for all of these cases to fix their error handling?
Ideally, the pattern would be something like this:
router.get('/whatever',async(req,res,next)=>{try{res.json(awaittrySomething());}catch(err){// you could also create a better external error to use here vs. exposing details about the internal problem...next(err);}});
We have a lot of express end-points that use
async
functions:Express 4.x doesn't quite do
async
properly, in that you have to manually deal with the error case and callnext(err)
manually so that errors propagate down the middleware chain to the eventual default error handler.The trick is to turn code like this:
into something like this:
Basically, we have to either deal with the error case in the route (i.e., don't let it go further in any code path), or call
next(err)
ourselves when things blow up. I haven't looked at all of our routes to see if they need changing, so this is a bug to audit things.The text was updated successfully, but these errors were encountered: