Kevin Powell - CommunityKP-C
Kevin Powell - Community10mo ago
9 replies
Ganesh

Error handling practices in ExpressJS

Hello everyone. I have recently started using express and was diving deeper into their docs when I came across the line in screenshot below. The page link is this https://expressjs.com/en/advanced/best-practice-performance.html#use-promises

What does it mean to handle errors as close to site as possible? does this mean just handle the error in the middleware that it happens in? What if I have multiple controller middlewares like one for validation and data fetching that calls next() to pass data to another middleware responsible for rendering/sending the view?

What if when an error happens I want to pass the view the message so it can show it to user.

app.post("sign-in", async (req, res) => {
  try {
    const doesUserAlreadyExist = await DB.getUser(req.body.user);
    if(doesUserAlreadyExist)
      throw new DatabaseError("user already exists");
    else
      next()
}

catch(err) {
  res.render("signup-form", {errMessage : err.message})
}
})


I feel like this is making the middleware that's just supposed to fetch data do something else by having it render on error. And what if I have another middleware before this that throws an error, I would need to put res.render in that too and that will lead to duplication of code.

So far I have handled the errors with just app wide error middleware that express recommends but I'm not sure what to do in the scenarios like above.
image.png
Was this page helpful?