简体   繁体   中英

Unhandled promise rejection with Joi

I'm having an issue with the script below after upgrading Joi v13 to ^17. The Joi docs state that Joi.validate is deprecated and schema.validate should be used but that is not working for me either. Postman just hangs until I have to cancel the request manually. Below is the code when making a post request to create a user:

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

And the server output:

(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.h andle [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.

The script can actually be found at the link below: Github

Try wrapping your Mongo requests in try/catch, because if they throw an error, they will be unhandled:

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

These are the only unhandled exceptions I can see, so hopefully it's one of them!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM