[英]Problem with catching error in Express application
Hello I have a problem witch catching errors in express.js application.您好,我在 express.js 应用程序中遇到错误捕获问题。 The problem is that next
call function in the controller. When I'm calling this function the error middleware aren't executing and I don't know why.问题是next
在 controller 中调用 function。当我调用这个 function 时,错误中间件没有执行,我不知道为什么。 I'm using Typescript.我正在使用 Typescript。
controller: controller:
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);
}
};
Error middleware:错误中间件:
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();
}
);
//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);
}
},
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.