Javascript 我已在承诺链中捕获(),但仍然未处理承诺拒绝

Javascript 我已在承诺链中捕获(),但仍然未处理承诺拒绝,javascript,node.js,express,promise,Javascript,Node.js,Express,Promise,我发现很多线程都有相同的问题,但几乎所有的线程都没有catch()或使用了错误的承诺链。 我正在测试当用户输入错误的密码或标识并且登录失败时的情况。 在我的代码中,我认为我在catch()中正确地使用了承诺链,但仍然出现未处理的承诺拒绝错误。 该网站应该显示错误消息“错误的密码”类似的网站上 代码是在node.js和express.js中编写的 这是我的代码: app.js 我知道我没有做密码加密,但我会做它以后当这个问题得到解决。 正如您在代码中看到的,当用户发送POST登录请求时,app.j

我发现很多线程都有相同的问题,但几乎所有的线程都没有catch()或使用了错误的承诺链。 我正在测试当用户输入错误的密码或标识并且登录失败时的情况。 在我的代码中,我认为我在catch()中正确地使用了承诺链,但仍然出现未处理的承诺拒绝错误。 该网站应该显示错误消息“错误的密码”类似的网站上

代码是在node.js和express.js中编写的

这是我的代码: app.js

我知道我没有做密码加密,但我会做它以后当这个问题得到解决。 正如您在代码中看到的,当用户发送POST登录请求时,app.js中的app.POST将验证数据,如果没有问题,它将从dbUserList.js调用dbFile.checkIfUserExists。dbUserList返回一个承诺,因此我在app.post中使用.then().catch()创建了一个承诺链

但我还是会

It seems like your id and password don't match. please try again with different id and password
(node:7896) UnhandledPromiseRejectionWarning: It seems like your id and password don't match. please try again with different id and password
(Use `node --trace-warnings ...` to show where the warning was created)
(node:7896) 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:7896) [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.

我发现console.log in then().catch()可以工作,因此两个try-catch中都应该没有任何问题,我无法理解为什么我的代码仍然显示未处理的承诺拒绝

事实上,您有一个未处理的承诺拒绝:

.catch((errMessage)=>{
  console.log(errMessage);
  throw errMessage;
})
.catch
位于承诺链的末尾,因此返回一个承诺。现在,如果您进入
catch
回调和
throw
,那么这将使该承诺处于拒绝状态,并且没有更多的拒绝处理程序

不要扔东西,你应该在那个地方正确地发送:

res.send({errorMessage: errMessage})

好吧,如果你在最后的
.catch
回调中抛出
,那么你确实有一个未经处理的拒绝承诺。@trincot哦,真的吗?你救了我的命。谢谢,但是如果throw调用拒绝,如何将错误数据发送到外部catch呢?catch在try-catch内部,我必须以某种方式将消息抛出catch()…不要尝试进入外部的
try-catch
块,因为该代码不能异步使用。只要在那个地方发送错误就行了。看到我的答案了。谢谢你,我自己几天都试图解决这个问题,但是我没能,你救了我的命!
.catch((errMessage)=>{
  console.log(errMessage);
  throw errMessage;
})
res.send({errorMessage: errMessage})