NodeJS 在Express应用程序中捕获错误时出现问题

iyfjxgzm  于 2022-12-12  发布在  Node.js
关注(0)|答案(1)|浏览(151)

你好,我在express.js应用程序中遇到了一个捕获错误的问题。问题是next调用控制器中的函数。当我调用这个函数时,错误中间件没有执行,我不知道为什么。我使用的是Typescript。
控制器:

const postCreateUser = async (
    req: Request,
    res: Response,
    next: NextFunction
) => {
    try {
        const { email, username, password, retypePassword } = req.body;
        const isEmailExist = await User.findOne({ where: { email: email } });
        if (isEmailExist) {
            let error: ResponseError = new Error("This email exists");
            error.status = 422;
            next(error);
        }
        const hashedPassword = await bcryptjs.hash(password, 12);
        const user = await User.create({
            username,
            email,
            password: hashedPassword,
        });
        res.status(201).json({ message: "User created succesfully." });
    } catch (err) {
        next(err);
    }
};

错误中间件:

app.use(
    (
        error: ResponseError,
        req: Request,
        res: Response,
        next: NextFunction
    ) => {
        const status = error.status || 500;
        console.log(error);

        res.status(status).json({ message: error.message });
        next();
    }
);
2nc8po8w

2nc8po8w1#

//This is my controller
let authController = {
    loginUser: async (req, res, next) => {
            try {
                const user = await userModel.findOne({
                    where: {
                        email: req.body.email
                    }
                });
                if (user) {
                const isMatched = await bcrypt.compare(req.body.password, user.password);
if (isMatched) {
                        const token = await jwt.createToken({
                            id: user.id,
                            name: user.name,
                            email: user.email,
                            created_at: user.created_at,
                            updated_at: user.updated_at
                        });
                        return res.status(200).json({
                            status: true,
                            message: 'Login Successfully',
                            access_token: token,
                            token_type: 'Bearer',
                            expires_in: jwtConfig.ttl
                        });
                    }
                }
                return res.status(400).json({
                    status: false,
                    message: 'Invalid email address or password please try again later!!!'
                });
            } catch (err) {
                next(err);
            }
        },
    };

相关问题