skip to Main Content

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


  1. 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.

        try {
        const data = await action.find({
            _id: id,
        }).populate({
            path: "child",
            match: (parent) => {
                try {
                    return {
                        property: test[undefined].property
                    };
                } catch (error) {
                    console.error("Error in match function:", error);
                    return {}; // or any default value
                }
            }
        });
         } catch (e) {
        console.log("Error happened:", e);
         }
      

    I hope this helps.

    Login or Signup to reply.
  2. 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 the action.find(...).populate(...) promise and thus can’t be caught by your await and try/catch.

    Remember this is an asynchronous error so it won’t be caught synchronously by your try/catch. The only way for your try/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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search