簡體   English   中英

Joi 未處理的承諾拒絕

[英]Unhandled promise rejection with Joi

將 Joi v13 升級到 ^17 后,我遇到了下面的腳本問題。 Joi 文檔聲明不推薦使用 Joi.validate 並且應該使用 schema.validate 但這對我也不起作用。 郵遞員只是掛起,直到我必須手動取消請求。 以下是發出帖子請求以創建用戶時的代碼:

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: E​​rror: Invalid message options at new module.exports (/Users/Username/chatapp/node_modules/@hapi/hoek/lib/error.js:23:19) at module.exports (/Users/用戶名/chatapp/node_modules/@hapi/hoek/lib/assert.js:20:11) 在 Object.exports.compile (/Users/Username/chatapp/node_modules/@hapi/joi/lib/messages.js:30: 5) 在 Object.exports.preferences (/Users/Username/chatapp/node_modules/@hapi/joi/lib/common.js:162:36) 在 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)在 CreateUser (/Users /Username/chatapp/controllers/auth.js:25:37)在 Layer.handle [as handle_request] (/Users/Username/chatapp/node_modules/express/lib/router/layer.js:95:5) 在下一個 ( /Users/Username/chatapp/node_modules/express/lib/router/route.js:137:13) 在 Route.dispatch (/Users/Username/chatapp/node_modules/express/lib/router/route.js:112:3 ) 在 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 在 Function.process_params (/Users/Username/chatapp/node_modules/express/lib/router/index.js:335:12) 下 (/Users/Username/chatapp/node_modules/express/lib/router/index.js:335:12) js:275:10) 在 Function.handle (/Users/Username/chatapp/node_modules/express/lib/router/index.js:174:3) 在路由器 (/Users/Username/chatapp/node_modules/express/lib/ router/index.js:47:12) (node:8787) UnhandledPromiseRejectionWarning:未處理的承諾拒絕。 這個錯誤要么是因為在沒有 catch 塊的情況下拋出了異步函數,要么是因為拒絕了一個沒有用 .catch() 處理過的承諾。 要在未處理的承諾拒絕時終止節點進程,請使用 CLI 標志--unhandled-rejections=strict (請參閱https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode )。 (rejection id: 1) (node:8787) [DEP0018] DeprecationWarning:不推薦使用未處理的承諾拒絕。 將來,未處理的承諾拒絕將使用非零退出代碼終止 Node.js 進程。

該腳本實際上可以在以下鏈接中找到: 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)
}

這些是我能看到的唯一未處理的異常,所以希望它是其中之一!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM