【发布时间】:2022-02-08 14:46:32
【问题描述】:
我正在研究 express 中的错误处理,我定义了一个。它适用于非异步函数。但是当涉及到异步功能时,应用程序就会崩溃。
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 });
});
我已将错误处理程序放在应用程序的底部,如下所示:
app.use((err, req, res, next) => {
const { status = 500, message = "something went wrong" } = err;
res.status(status).send(message);
});
我的自定义错误类:
class AppError extends Error {
constructor(message, status) {
super();
this.message = message;
this.status = status;
}
}
module.exports = AppError;
【问题讨论】:
标签: node.js express error-handling