Express.js错误处理程序在第一个之后被忽略。

huangapple go评论126阅读模式
英文:

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

问题

我有一个使用Express.js编写的应用程序,其中包含一些路由和一个受保护的路由,该路由匹配以/app开头的所有端点的调用。之后,我像这样向应用程序添加了通用错误处理程序:

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

// app.post("/new_user", validate({body: schema}), route_handler);
// 更多路由等等

app.use((error: TypeError | ValidationError, req: Request, res: Response, next: NextFunction) => {
    console.log("检查验证错误");
    if (error instanceof ValidationError) {
        console.log("找到验证错误");
        res.status(403).send(error);
    } else {
        console.log("没有验证错误");
        next();
    }
});

app.use((error: TypeError | AuthError, req: Request, res: Response, next: NextFunction) => {
    console.log("检查身份验证错误");
    if (error instanceof AuthError) {
        console.log("找到身份验证错误");
        res.status(403).send({ msg: "身份验证失败" });
    } else {
        console.log("没有身份验证错误");
        next();
    }
});

app.use((error: Error, req: Request, res: Response, next: NextFunction) => {
    console.log("检查通用错误");
    if (error) {
        res.status(500).send({ msg: "发生了一些通用错误" });
    } else {
        next();
    }
});

app.use((req: Request, res: Response, next: NextFunction) => {
    console.log("路由未找到");
    res.status(404).send({
        msg: "未找到此端点",
    });

    next();
});

当我对例如以下端点进行请求:https://localhost/app/ 并在此端点故意抛出 AuthError 时,我看到的唯一的 console.log() 是:

检查验证错误
没有验证错误
路由未找到

但我认为我应该看到以下内容:

检查验证错误
没有验证错误
检查身份验证错误
找到身份验证错误

为什么我的身份验证错误中间件从未被调用?

英文:

I have an express js app with some routes and a protected route that matches all the calls to an endpoint that starts with /app. after that i add generic error handler to the app like so:


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();
    });

When i do a request to for example the following endpoint: https://localhost/app/ and throw a AuthError on purpose in this endpoint the only console.log()'s i ever see are:

CHECK FOR VALIDATION ERROR
NO VALIDATION ERROR
ROUTE NOT FOUND

But i think i should see the following:

CHECK FOR VALIDATION ERROR
NO VALIDATION ERROR
CHECK FOR AUTH ERROR
AUTH ERROR FOUND

Why is my Auth error middleware never called??

答案1

得分: 1

你需要在调用 next 时将 error 传递给其他错误中间件,像这样:

app.use((error: TypeError | AuthError, req: Request, res: Response, next: NextFunction) => {
    console.log("检查身份验证错误");
    if (error instanceof AuthError) {
        console.log("找到身份验证错误");
        res.status(403).send({ msg: "身份验证失败" });
    } else {
        console.log("没有身份验证错误");
        next(error);
    }
});

没有这样做的话,正常的中间件会被调用。

英文:

You need to pass error to the other error middleware when you call next like this:

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);
        }
    });

Without it, the normal middleware will get called.

huangapple
  • 本文由 发表于 2023年6月1日 17:55:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76380711.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定