Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs Promise reject wont forward error messages

Im trying to catch an error that says the file that im trying to read does not exist. i have intentionally named the file wrong.

inside my controller i have getAllProducts() that will return a promise, if the promise resolves then i render a page, if not then display the error to the console

// inside productController.js 
exports.getProductForShop = (req, res, next) => {
    productModel.getAllProducts()
        .then(products => {
            res.render('shop', {
                title: 'shop',
                products,
                path: '/'
            });
        })
        .catch((error) => {
            console.log(error);
        });
}

inside my model class i have implemented the above mention function ie: getAllProducts()here is the code its a static function, if that's anything of importance

// inside productModel.js
static getAllProducts() {
    return new Promise((resolve, reject) => {
        fs.readFile('data/wrongName.json', (error, products) => { // wrong file name
            if (error) {
                reject(new Error(error)); // <-- line that sends error message
            }

            resolve(JSON.parse(products)); // this is line 52, it should not be executed
        })
    })
}

when i run the code i get the following error message

SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at ReadFileContext.callback (C:\Users\user\Desktop\JS\NodeJs\models\productModel.js:52:30)
?[90m    at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:239:13)?[39m

this must mean that the fs.readFile received the wrong file name, threw an error, reject(new Error(error)); was called, still went on to execute line 52 which has resolve();

when i console log the error inside the if(error) block i get the correct error message

Error: Error: ENOENT: no such file or directory, open 'C:\Users\user\Desktop\JS\NodeJs\data\wrongName.json'
    at ReadFileContext.callback (C:\Users\user\Desktop\JS\NodeJs\models\productModel.js:49:35)
    at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:239:13)

when i do return reject(new Error(error)); i get the correct error message, same as show above.

Can someone please explain to me why the error message passed to reject(new Error(error)); is not caught in the catch block ?

Update: adding catch block did not work either, seems that a return render is the only way?! i was under the impression that reject puts the promise in a rejected state and prevents further execution

// inside productModel.js
static getAllProducts() {
    return new Promise((resolve, reject) => {
        fs.readFile('data/productseData.json', (error, products) => {
            if (error) {
                reject(new Error(error));
            }

            resolve(JSON.parse(products));
        })
    }).catch((error) => {
        console.log(error);
    })
}
like image 694
some_groceries Avatar asked Oct 28 '25 05:10

some_groceries


1 Answers

You have a slight misunderstanding of what's going on here. Calling reject will reject the promise, and the subsequent resolve will not resolve it. So far so good. The problem is that it won't stop execution without a return. So you're essentially running unnecessary code which happens to cause an error.

You should ensure that the resolve code is not executed in the case of an error. You can accomplish this with return reject or by wrapping the resolve in an else block.

Keep in mind there's nothing special about resolve/reject here. They're simple function calls and function calls do nothing to stop execution.

like image 115
aw04 Avatar answered Oct 29 '25 19:10

aw04



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!