簡體   English   中英

當異步身份驗證登錄功能出現新異常時,Express 服務器崩潰

[英]Express server crash when new exception in async auth login function

這個問題讓我發瘋了......我有一個拋出異常,使我的快速服務器在我的異步登錄功能中崩潰。 問題是錯誤沒有傳遞到 try/catch 的捕獲中。 用戶數據從數據庫中得到很好的接收。

如果在我的 bcrypt 函數之外拋出,新的 throw 異常可以正常工作。

module.exports.login = async (req, res, next) => {
  try {
    const {
      username,
      password
    } = req.body;
    if (!username) {
      throw new MissingRequiredParameterError({
        info: {
          body: ['usename']
        }
      });
    }

    if (!password) {
      throw new MissingRequiredParameterError({
        info: {
          body: ['password']
        }
      });
    }
    const user = await User.find({
      username: username
    }).exec();

    // throw new BadCredentialsError({                 // Exception works fine
    //   message: 'Username or password is incorrect'  // if those lines
    // });                                             // are uncommented

    if (user != '') {
      await bcrypt.compare(password, user[0].password, (errBcrypt, resBcrypt) => {
        if (!resBcrypt) {                              // is false if password is wrong
          throw new BadCredentialsError({ // Line 85 THIS Exceptions makes my server crash if password is wrong !
            message: 'Username or password is incorrect'
          });
        } else {
          // Generate token
          const {
            accessToken,
            refreshToken
          } = await generateToken(user[0]);

          await res.json({
            accessToken,
            accessTokenExpiresIn: config.accessToken.expiresIn,
            refreshToken,
            refreshTokenExpiresIn: config.refreshToken.expiresIn
          });
        }
      });
    } else {
      throw new BadCredentialsError({
        message: 'Username or password is incorrect'
      });
    }


  } catch (err) {
    console.error('pass', err.stack);
    next(err);
  }
};

看到崩潰:

C:\Users\rebeb\Attila\attila-srv\api\controllers\auth.js:85
          throw new BadCredentialsError({
                ^
bad_credentials: Username or password is incorrect
    at C:\Users\rebeb\Attila\attila-srv\api\controllers\auth.js:85:17 {
  jse_shortmsg: 'Username or password is incorrect',
  jse_info: {},
  isHTTPError: true,
  status: 401,
  expose: true
}
[nodemon] app crashed - waiting for file changes before starting...

它應該是這樣的:

var resBcrypt = await bcrypt.compare(password, user[0].password); 在沒有回調的情況下繼續之前。

發生的事情是錯誤是在回調本身中拋出的,而不是在與 await 調用相同的代碼流中。

如果該方法不支持基於 promise 的語法,您可能必須先“promisify”該方法。

https://javascript.info/promisify

暫無
暫無

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

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