Hello i’m encounter an issue i don’t understand:
i’m having an uncaught error in my nodejs application, that I can’t catch even in a try…catch sentence.
I’m using mongoose 5, error not occur in above version, so I will update but I want to understand why my error is not catch here:
try {
const data = await action.find({
_id: id,
}).populate({
path: "child",
match: (parent) => ({
property: test[undefined].property
})
});
} catch (e) {
console.log("error happen");
}
I know i’ll get an error due to the test[undefined].property, and console log error happen,
but instead i get an uncaught error :
/mongodb/lib/utils.js:113
throw err;
^
TypeError: Cannot read properties of undefined (reading 'program')
I don’t understand why it’s not actually catch by my try..catch.
2
Answers
Exception Handling in Asynchronous Code
As you can see, the code is multilevel, i.e. multiple nesting of functions. And if you are trying to handle the exceptions, you should consider the levels appropriately.
You can handle an exception in the same level
Or pass the exception to the outer level by returning it.
I hope this helps.
This seems to be a bug (or improper design) in the database code. You’re supplying a
match
callback that the database will call at some time of its choosing (asynchronously) in the processing of the.populate()
method. When it gets an exception from calling that callback (deep down in the database code where it called the callback), it is NOT propagating that error back to theaction.find(...).populate(...)
promise and thus can’t be caught by yourawait
andtry/catch
.Remember this is an asynchronous error so it won’t be caught synchronously by your
try/catch
. The only way for yourtry/catch
to catch an asynchronous error is for the DB to catch it when it happens and turn it into rejecting the promise that was originally returned by the DB call.