Error Handling

View saved

try / catch with await

Handle expected failures near the call site.

try {
  const text = await readFile("missing.txt", "utf8");
  console.log(text);
} catch (err) {
  console.error("Could not read file:", err.message);
  process.exitCode = 1;
}

Express error middleware

Handlers with four arguments catch next(err) failures.

app.get("/boom", (req, res, next) => {
  next(new Error("Something broke"));
});

app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: "Internal server error" });
});

Validate input early

Return 400 with a clear message when the client sends bad data.

if (!req.body?.title) {
  return res.status(400).json({ error: "title is required" });
}

Log safely

Log details on the server. Send generic messages to clients for unexpected 500s.

Comments

One comment per signed-in account. Comments are saved with this page’s URL.