NodeJS express js error handler(s)get ignored after first one

jdg4fx2g  于 2023-06-05  发布在  Node.js
关注(0)|答案(1)|浏览(143)

我有一个express js应用程序,其中包含一些路由和一个受保护的路由,该路由匹配所有对以/app开头的端点的调用。在那之后,我向应用程序添加通用错误处理程序,如下所示:

app.use("/app", authenticate);

// app.post("/new_user", validate({body: schema}), route_handler);
// more routes etc. 

app.use((error: TypeError | ValidationError, req: Request, res: Response, next: NextFunction) => {
        console.log("CHECK FOR VALIDATION ERROR");
        if(error instanceof ValidationError) {
            console.log("VALIDATION ERROR FOUND")
            res.status(403).send(error);
        } else {
            console.log("NO VALIDATION ERROR")
            next();
        }
    });

    app.use((error: TypeError | AuthError, req: Request, res: Response, next: NextFunction) => {
        console.log("CHECK FOR AUTH ERROR");
        if(error instanceof AuthError) {
            console.log("AUTH ERROR FOUND");
            res.status(403).send({msg: "Authentication failed"});
        } else {
            console.log("NO AUTH ERROR")
            next();
        }
    });

    app.use((error: Error, req: Request, res: Response, next: NextFunction) => {
        console.log("CHECK GENERIC ERROR");
        if(error) {
            res.status(500).send({msg: "Some generic error happend"});
        } else {
            next();
        }
    });

    app.use((req: Request, res: Response, next: NextFunction) => {
        console.log("ROUTE NOT FOUND");
        res.status(404).send({
            msg: "this endpoint was not found",
        });

        next();
    });

例如,当我向以下端点发出请求时:https://localhost/app/并故意抛出一个AuthError在这个端点中,我见过的唯一的console.log()是:
检查验证错误
无验证错误
未找到路由
但我想我应该看到以下几点:
检查验证错误
无验证错误
检查授权错误
发现授权错误
为什么我的Auth错误中间件从未被调用??

u4dcyp6a

u4dcyp6a1#

在调用next时,需要将error传递给另一个错误中间件,如下所示:

app.use((error: TypeError | AuthError, req: Request, res: Response, next: NextFunction) => {
        console.log("CHECK FOR AUTH ERROR");
        if(error instanceof AuthError) {
            console.log("AUTH ERROR FOUND");
            res.status(403).send({msg: "Authentication failed"});
        } else {
            console.log("NO AUTH ERROR")
            next(error);
        }
    });

如果没有它,正常的中间件将被调用。

相关问题