Back

Error Handling

Express has a special error-handling middleware with four arguments (err, req, res, next). Put it after all your routes so any error ends up in one place and returns a clean response.

app.get("/users/:id", async (req, res, next) => {
  try {
    const user = await findUser(req.params.id)
    if (!user) return res.status(404).json({ error: "Not found" })
    res.json(user)
  } catch (err) {
    next(err)  // send to error handler
  }
})

// Error handler: must be last
app.use((err, req, res, next) => {
  console.error(err)
  res.status(500).json({ error: "Something went wrong" })
})

Roadmap