Handling rejected promises:
router.get("/", async (req, res) => {
try {
const genres = await Genre.find().sort("name");
res.send(genres);
} catch (ex) {
res.status(500).send("Unexpected error occured !");
}
});
We have a special middleware called error middleware. that we use after defining all the middleware
app.use(json());
app.use("/api/genres", genres);
app.use("/api/customers", customers);
app.use("/api/users", users);
app.use("/api/auth", auth);
app.use(function (err, req, res, next) {
res.status(500).send("Unexpected Error occured");
});
and now change the above code to
router.get("/", async (req, res, next) => {
try {
const genres = await Genre.find().sort("name");
res.send(genres);
} catch (ex) {
// this will call the error middleware
next(ex);
}
});
use a package
npm i express-async-errors
use a package called winston
it is as object that can emit or publish event
Handling uncaught exceptions