Joi 未处理的承诺拒绝
Unhandled promise rejection with Joi
将 Joi v13 升级到 ^17 后,我遇到以下脚本问题。 Joi 文档声明 Joi.validate 已弃用,应该使用 schema.validate 但这对我也不起作用。邮递员只是挂起,直到我必须手动取消请求。下面是发出 post 创建用户请求时的代码:
const Joi = require("@hapi/joi");
const HttpStatus = require("http-status-codes");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const User = require("../models/userModels");
const Helpers = require("../Helpers/helpers");
const dbConfig = require("../config/secret");
module.exports = {
async CreateUser(req, res) {
const schema = Joi.object().keys({
username: Joi.string()
.min(5)
.max(10)
.required(),
email: Joi.string()
.email()
.required(),
password: Joi.string()
.min(5)
.required()
});
const { error, value } = schema.validate(req.body, schema);
if (error && error.details) {
return res.status(HttpStatus.BAD_REQUEST).json({ msg: error.details });
}
const userEmail = await User.findOne({
email: Helpers.lowerCase(req.body.email)
});
if (userEmail) {
return res
.status(HttpStatus.CONFLICT)
.json({ message: "Email already exist" });
}
const userName = await User.findOne({
username: Helpers.firstUpper(req.body.username)
});
if (userName) {
return res
.status(HttpStatus.CONFLICT)
.json({ message: "Username already exist" });
}
return bcrypt.hash(value.password, 10, (err, hash) => {
if (err) {
return res
.status(HttpStatus.BAD_REQUEST)
.json({ message: "Error hashing password" });
}
const body = {
username: Helpers.firstUpper(value.username),
email: Helpers.lowerCase(value.email),
password: hash
};
User.create(body)
.then(user => {
const token = jwt.sign({ data: user }, dbConfig.secret, {
expiresIn: "5h"
});
res.cookie("auth", token);
res
.status(HttpStatus.CREATED)
.json({ message: "User created successfully", user, token });
})
.catch(err => {
res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: "Error occured" });
});
});
}
};
并且服务器输出:
(node:8787) UnhandledPromiseRejectionWarning: Error: Invalid message
options
at new module.exports (/Users/Username/chatapp/node_modules/@hapi/hoek/lib/error.js:23:19)
at module.exports (/Users/Username/chatapp/node_modules/@hapi/hoek/lib/assert.js:20:11)
at Object.exports.compile (/Users/Username/chatapp/node_modules/@hapi/joi/lib/messages.js:30:5)
at Object.exports.preferences (/Users/Username/chatapp/node_modules/@hapi/joi/lib/common.js:162:36)
at Object.exports.entry (/Users/Username/chatapp/node_modules/@hapi/joi/lib/validator.js:23:27)
at internals.Base.validate (/Users/Username/chatapp/node_modules/@hapi/joi/lib/base.js:536:26)
at CreateUser (/Users/Username/chatapp/controllers/auth.js:25:37)
at Layer.handle [as handle_request] (/Users/Username/chatapp/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/Username/chatapp/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/Username/chatapp/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/Username/chatapp/node_modules/express/lib/router/layer.js:95:5)
at /Users/Username/chatapp/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/Username/chatapp/node_modules/express/lib/router/index.js:335:12)
at next (/Users/Username/chatapp/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/Users/Username/chatapp/node_modules/express/lib/router/index.js:174:3)
at router (/Users/Username/chatapp/node_modules/express/lib/router/index.js:47:12)
(node:8787) UnhandledPromiseRejectionWarning: Unhandled promise
rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was
not handled with .catch(). To terminate the node process on unhandled
promise rejection, use the CLI flag --unhandled-rejections=strict
(see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).
(rejection id: 1) (node:8787) [DEP0018] DeprecationWarning: Unhandled
promise rejections are deprecated. In the future, promise rejections
that are not handled will terminate the Node.js process with a
non-zero exit code.
脚本实际上可以在下面的 link 找到:
Github
尝试将您的 Mongo 请求包装在 try/catch 中,因为如果它们抛出错误,它们将无法处理:
try {
const userEmail = await User.findOne({
email: Helpers.lowerCase(req.body.email)
})
if (userEmail) {
return res
.status(HttpStatus.CONFLICT)
.json({ message: 'Email already exist' })
}
const userName = await User.findOne({
username: Helpers.firstUpper(req.body.username)
})
if (userName) {
return res
.status(HttpStatus.CONFLICT)
.json({ message: 'Username already exist' })
}
} catch (err) {
console.error(err)
}
这些是我能看到的唯一未处理的异常,所以希望它是其中之一!
将 Joi v13 升级到 ^17 后,我遇到以下脚本问题。 Joi 文档声明 Joi.validate 已弃用,应该使用 schema.validate 但这对我也不起作用。邮递员只是挂起,直到我必须手动取消请求。下面是发出 post 创建用户请求时的代码:
const Joi = require("@hapi/joi");
const HttpStatus = require("http-status-codes");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const User = require("../models/userModels");
const Helpers = require("../Helpers/helpers");
const dbConfig = require("../config/secret");
module.exports = {
async CreateUser(req, res) {
const schema = Joi.object().keys({
username: Joi.string()
.min(5)
.max(10)
.required(),
email: Joi.string()
.email()
.required(),
password: Joi.string()
.min(5)
.required()
});
const { error, value } = schema.validate(req.body, schema);
if (error && error.details) {
return res.status(HttpStatus.BAD_REQUEST).json({ msg: error.details });
}
const userEmail = await User.findOne({
email: Helpers.lowerCase(req.body.email)
});
if (userEmail) {
return res
.status(HttpStatus.CONFLICT)
.json({ message: "Email already exist" });
}
const userName = await User.findOne({
username: Helpers.firstUpper(req.body.username)
});
if (userName) {
return res
.status(HttpStatus.CONFLICT)
.json({ message: "Username already exist" });
}
return bcrypt.hash(value.password, 10, (err, hash) => {
if (err) {
return res
.status(HttpStatus.BAD_REQUEST)
.json({ message: "Error hashing password" });
}
const body = {
username: Helpers.firstUpper(value.username),
email: Helpers.lowerCase(value.email),
password: hash
};
User.create(body)
.then(user => {
const token = jwt.sign({ data: user }, dbConfig.secret, {
expiresIn: "5h"
});
res.cookie("auth", token);
res
.status(HttpStatus.CREATED)
.json({ message: "User created successfully", user, token });
})
.catch(err => {
res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: "Error occured" });
});
});
}
};
并且服务器输出:
(node:8787) UnhandledPromiseRejectionWarning: Error: Invalid message options at new module.exports (/Users/Username/chatapp/node_modules/@hapi/hoek/lib/error.js:23:19) at module.exports (/Users/Username/chatapp/node_modules/@hapi/hoek/lib/assert.js:20:11) at Object.exports.compile (/Users/Username/chatapp/node_modules/@hapi/joi/lib/messages.js:30:5) at Object.exports.preferences (/Users/Username/chatapp/node_modules/@hapi/joi/lib/common.js:162:36) at Object.exports.entry (/Users/Username/chatapp/node_modules/@hapi/joi/lib/validator.js:23:27) at internals.Base.validate (/Users/Username/chatapp/node_modules/@hapi/joi/lib/base.js:536:26) at CreateUser (/Users/Username/chatapp/controllers/auth.js:25:37) at Layer.handle [as handle_request] (/Users/Username/chatapp/node_modules/express/lib/router/layer.js:95:5) at next (/Users/Username/chatapp/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/Users/Username/chatapp/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/Users/Username/chatapp/node_modules/express/lib/router/layer.js:95:5) at /Users/Username/chatapp/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/Users/Username/chatapp/node_modules/express/lib/router/index.js:335:12) at next (/Users/Username/chatapp/node_modules/express/lib/router/index.js:275:10) at Function.handle (/Users/Username/chatapp/node_modules/express/lib/router/index.js:174:3) at router (/Users/Username/chatapp/node_modules/express/lib/router/index.js:47:12) (node:8787) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag
--unhandled-rejections=strict
(see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:8787) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
脚本实际上可以在下面的 link 找到: Github
尝试将您的 Mongo 请求包装在 try/catch 中,因为如果它们抛出错误,它们将无法处理:
try {
const userEmail = await User.findOne({
email: Helpers.lowerCase(req.body.email)
})
if (userEmail) {
return res
.status(HttpStatus.CONFLICT)
.json({ message: 'Email already exist' })
}
const userName = await User.findOne({
username: Helpers.firstUpper(req.body.username)
})
if (userName) {
return res
.status(HttpStatus.CONFLICT)
.json({ message: 'Username already exist' })
}
} catch (err) {
console.error(err)
}
这些是我能看到的唯一未处理的异常,所以希望它是其中之一!