正确处理承诺拒绝

时间:2019-05-09 15:30:12

标签: javascript node.js asynchronous

考虑以下代码:

db.js

// Connecting to catalogstore (mongodb)
const mydb = async () => {
  try {
    await mongoose.connect(process.env.db);
    console.log("Connected to Database!");
  }
  catch (err) {
    throw new Error("Database connection error:", err);
  }
};

export { db }

app.js

import { db } from './db';
db().then(async() => {
  try {
    let server = app.listen(process.env.port,
      process.env.host, function() {
        let host = server.address().address;
        let port = server.address().port;
        console.log('App started');
    });
  } catch (err) {
    console.log(err);
  }
});

基本上,我只想在建立数据库连接后启动Express服务器。

它实际上工作正常,但是我收到此警告:

(node:29892) UnhandledPromiseRejectionWarning: Error: Database connection error:
    at catalogstore (/Users/notaris/Workspace/Google/gcp-devops/apps/catalogservice/src/db.js:44:11)
    at processTicksAndRejections (internal/process/task_queues.js:89:5)
(node:29892) 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(). (rejection id: 1)
(node:29892) [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.

我该如何正确处理?

3 个答案:

答案 0 :(得分:1)

db异步函数引发了错误。

处理此Error(使用异步函数/箭头)的正确方法是:

import { db } from './db';
const main = async () => {
  try {
    await db();
    let server = app.listen(process.env.port,
      process.env.host, function() {
        let host = server.address().address;
        let port = server.address().port;
        console.log('App started');
    });
  } catch (err) {
    console.log(err);
  }
});
main();

答案 1 :(得分:1)

按如下所述修改app.js

import { db } from './db';
db()
  .then(/* normal logic */)
  .catch(/* error logic */)

只需抓住它^^

答案 2 :(得分:-1)

在调试器中,我看到您应该在promise中捕获这样的错误:

//app.js
import { db } from './db';
db().then(async() => {
  try {
    let server = app.listen(process.env.port,
      process.env.host, function() {
        let host = server.address().address;
        let port = server.address().port;
        console.log('App started');
    });
  } catch (err) {
    console.log(err);
  }
}).catch(error=>{
     console.log('error'+error);
});

您可以检查此link以获得更多详细信息。