自定义错误处理程序在 NodeJs Express 中不起作用
Custom Error Handler not working in NodeJs Express
我在研究 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:
class AppError extends Error {
constructor(message, status) {
super();
this.message = message;
this.status = status;
}
}
module.exports = AppError;
我相信您的路由器在等待由于某种原因失败时不知道该怎么办。您可以使用我在下面制作的这个 catchAsync,但您也可以围绕您的代码执行 try
catch
语句,以便它捕获错误并继续执行下一个任务。
try/catch 可能看起来像这样
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());
}
});
这是我的 catch 异步函数,您可以使用。
module.exports = func => {
return (req, res, next) => {
func(req, res, next).catch(next);
}
}
如果这不能解决问题,请告诉我
我在研究 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:
class AppError extends Error {
constructor(message, status) {
super();
this.message = message;
this.status = status;
}
}
module.exports = AppError;
我相信您的路由器在等待由于某种原因失败时不知道该怎么办。您可以使用我在下面制作的这个 catchAsync,但您也可以围绕您的代码执行 try
catch
语句,以便它捕获错误并继续执行下一个任务。
try/catch 可能看起来像这样
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());
}
});
这是我的 catch 异步函数,您可以使用。
module.exports = func => {
return (req, res, next) => {
func(req, res, next).catch(next);
}
}
如果这不能解决问题,请告诉我