1

Problem

My try doesn't catch error if it is inside of MongoClients connect function


Environment

  • Linux (Mint, Tessa)
  • Node.js v10.16.0 (using ES6 with nodemon)
  • MongoClient (from mongodb npm repository)

Example

If I try this:

try {
    throw new Error('This is error');
} catch(e) {
    console.log(`Catched: ${e}`);
}

I get clean exit (it's fine - working)

Catched: Error: This is error
[nodemon] clean exit - waiting for changes before restart

But this doesn't work

If I try it in MongoDBs connect function:

try {
   MongoClient.connect(config.url, config.options, (err, db) => {
      if (err) { throw new Error('This is error'); }
   });
} catch (err) {
   console.log(`Catched: ${e}`);
}

I get app crashed

Error: This is error
[nodemon] app crashed - waiting for file changes before starting...

So it means it didn't catch my exception.

Dharman
  • 30,962
  • 25
  • 85
  • 135
JaxProx
  • 15
  • 6

1 Answers1

1

Try this

try {
   let db = await MongoClient.connect(config.url, config.options);
} catch (err) {
   console.log(`Catched: ${err}`);
}

Try to write code in async-await/sequential style if you want try catch to work.

Here you can see that you're getting err as first argument in callback, why would it go to catch block ? Same thing happens with func1().then().catch() style code.

Note: use async keyword in front of your function name if you want to use await.

eg:

async function test() {
   try {
   let db = await MongoClient.connect(config.url, config.options);
} catch (err) {
   console.log(`Catched: ${err}`);
} 
}

MongoClient.connect(config.url, config.options, (err, db) => {
      if (err) { throw new Error('This is error'); }
   });
Raj Kumar
  • 783
  • 1
  • 8
  • 23
  • Nice catch! I didn't thought that Mongo works asynchronous. At all I don't understand your solution with `await` (like where do the success block goes into?). But `then` and `catch` work well. – JaxProx Sep 30 '19 at 13:20
  • which success block are you talking about ? you can find some more details about try catch with async-await sytax here: https://stackoverflow.com/questions/44663864/correct-try-catch-syntax-using-async-await – Raj Kumar Sep 30 '19 at 13:26
  • I understand but in your `eg:` block, you have defined `async test()` function but where does the resolved variables go? You are catching only `err` but there is no more `db` variable. If I've tried to take my code (where is callback function where is set both `err` and `db` and put `await` before it (+ called in async fction) - it didn't catch anything. – JaxProx Sep 30 '19 at 13:33