NodeJSでエラーを投げる - UnhandledPromiseRejectionを

ロレンツォ・ファブロ:

私はNodeJSにかなり新たなんだと、私はまだエラーを処理する方法を把握しようとしています。私は多くの質問を読んで、私は私が間違ってやっている気付いていません。

ここで私は、ログイン機能を持っています:

export const login = async (req, res) => {
let body = req.body;

try {
  const user = await User.findOne({ username: body.username });

if (!user) {
  throw new InternalError("Username or password are wrong");
}

if (!bcrypt.compareSync(body.password, user.password)) {
  throw new InternalError("Username or password are wrong");
}

let token = jwt.sign({ data: user }, "secret", {
  expiresIn: 60 * 60 * 24 * 30
});

return res.json({
  user: user,
  token: token
 });
} catch (error) {
throw new GenericError(error);
 }
};

そして、これは私が、例えば、私は間違ったパスワードが含まれている場合取得エラーです。

(node:12332) UnhandledPromiseRejectionWarning: GenericError: Username or password are wrong
(node:12332) 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()

私が持っている必要があります待つと約束を知っている.then()し、.catch()これは約束を実行するのが、パスワードを検証上のエラーではありません。私が欲しいのは、エラーをスローし、応答を取得することです。今要求は決して終わりませんし、前のエラーが表示されます。

ありがとうございました!

PS:InternalErrorとGenericErrorがエラーから延び、私が作成したばかりのエラーです

nrayburnハイテク:

あなたがInternalErrorをキャッチした後GenericErrorを再投げているので、あなたはノードから警告を受けます。代わりにGenericErrorを再スローする、あなたはあなたの応答を返すべきか、呼び出し時に、あなたのGenericErrorをキャッチlogin

ここでは、両方のために変更され、あなたのコードがあります。

export const login = async (req, res) => {
  // We get the body info
  let body = req.body;

  try {
    // We find the user with the username from the body
    const user = await User.findOne({ username: body.username });

    // Let's assume no user exists, so we throw an InternalError,
    // This skips straight to the catch block.
    if (!user) {
      throw new InternalError("Username or password are wrong");
    }

    // We never reach these two statements
    // because of the error above being thrown.
    if (!bcrypt.compareSync(body.password, user.password)) {
      throw new InternalError("Username or password are wrong");
    }

    let token = jwt.sign({ data: user }, "secret", {
      expiresIn: 60 * 60 * 24 * 30
    });

   res.json({
      user: user,
      token: token
    });
  } catch (err) {
    // We caught our InternalError from not having a user above.
    // Now we should return a response that the user is invalid.
    // I am just going to return the error that we previously threw.
   res.json({
      error: err
    });
  }
};

あなたは間違いなくあなたのcatchブロックからGenericErrorを投げることができます。しかし、その後、それを行うことは、あなたのログイン機能を呼び出しているところはどこでもGenericErrorをキャッチする必要があります。

export const login = async (req, res) => {
  // We get the body info
  let body = req.body;

  try {
    // We find the user with the username from the body
    const user = await User.findOne({ username: body.username });

    // Let's assume no user exists, so we throw an InternalError,
    // This skips straight to the catch block.
    if (!user) {
      throw new InternalError("Username or password are wrong");
    }

    // We never reach these two statements
    // because of the error above being thrown.
    if (!bcrypt.compareSync(body.password, user.password)) {
      throw new InternalError("Username or password are wrong");
    }

    let token = jwt.sign({ data: user }, "secret", {
      expiresIn: 60 * 60 * 24 * 30
    });

   res.json({
      user: user,
      token: token
    });
  } catch (err) {
    // Throw the generic error
    throw GenericError(err);
  }
};


try {
  // We call the login function that is defined above.
  // It is going to throw a GenericError, so we have to
  // catch it.
  await login(req, res);
} catch (err) {
  // Now we need to catch the generic error
  res.json({
    error: err
  });
}

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=377631&siteId=1