Reputation: 170
I was studying about error handeling in express and I defined one. It works fine for non async functions. But when it comes to async function the app just breaks.
app.get("/products/:id", async (req, res, next) => {
const { id } = req.params;
const product = await Product.findById(id);
if (!product) {
return next(new AppError());
}
res.render("products/show", { product });
});
I have put the error handler at the bottom of the app like this:
app.use((err, req, res, next) => {
const { status = 500, message = "something went wrong" } = err;
res.status(status).send(message);
});
My custom Error Class:
class AppError extends Error {
constructor(message, status) {
super();
this.message = message;
this.status = status;
}
}
module.exports = AppError;
Upvotes: 0
Views: 1275
Reputation: 36
I believe your router doesn't know what to do when it the await fails for whatever reason. You can use this catchAsync I made below but you can also do a try
catch
statement around your code so it catches the error and goes onto the next task.
The try/catch could look something like this
app.get("/products/:id", async (req, res, next) => {
try{
const { id } = req.params;
const product = await Product.findById(id);
res.render("products/show", { product });
} catch(err) {
return next(new AppError());
}
});
This is my catch async function that you can use.
module.exports = func => {
return (req, res, next) => {
func(req, res, next).catch(next);
}
}
Please let me know if this doesn't solve the problem
Upvotes: 1