所以我使用express-async-handler来处理异步函数,它应该在抛出错误后自动添加next(),但由于某种原因它看起来没有。
这是我的函数示例:
const getCourse = asyncHandler(async (req, res, next) => {
const courseId = req.params.id;
if (courseId.length !== 24) {
throw new Error("Invalid course Id.");
}
const course = await Course.findById(courseId);
if (!course) {
return res.status(404).json({
error: "Course not found.",
});
}
res.status(200).json(course);
});
如果抛出任何错误,我会得到以下输出:
Listening on port 1337
/home/legasi/moonWebAcademy/backend/src/controllers/course-controller.js:51
throw new Error("Invalid course Id."); // or throw new InvalidIdFormatError("Invalid course Id.");
^
Error: Invalid course Id.
并且应用程序在抛出错误后崩溃。我的 app.js 中有一个错误处理程序中间件,但错误永远不会到达它:
app.use(courseRoute);
app.use((err, req, res, next) => {
console.log("1");
res.status(err.status || 500).json({ error: err.message });
});
这是我在路由器中注册它的方法:
router.route("/api/courses/:id")
.put(courseUpdateValidationRules, (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
updateCourse(req, res);
})
.delete((req, res) => {
deleteCourse(req, res);
})
.get((req,res) => {
getCourse(req,res)
});
我真的不知道该怎么办以及如何解决这个问题。谢谢!
我相信如果它抛出一个错误而不是在 try-catch 块中,它会使进程退出。
你尝试过 try-catch 包装吗?