Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my try\catch not catching an error in node.js

I have a block of code with a try catch wrapped around it. Inside the try block I am using a JSON query library called JSONata. In some cases when an undesireable string is mistakenly passed to the library the library with throw an error. My problem is that my catch block is not being hit, the app just crashes?

Here is some pseudo code to explain whats happening. The problem is when a user mistakenly puts the ] at the end of the id the evaluate function throws an error. My assumption was that when the error was thrown that my catch block would pick it up and send the error message to the browser. Instead my app just crashes.

try{
    let data = <some JSON data here>;
    let expression = jsonata("rows[userID=abc123]'])"
    expression.evaluate(data).then(result => {
        res.send(result)
    }    
}catch(err)
{ 
    res.send(err)
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As Dave mentioned, you can use .catch

try {
    let data = {};
    let expression = foo();
    expression.promiseFoo.then(result => {
        res.send(result)
    }).catch(err => {
        res.send(err);
    })
} catch (err) { 
    res.send(err)
}

Also, if you’re using async/await you can do something like:

router.get('/', async function(req, res, next) {
    try {
        let data = {};
        let expression = foo();
        const result = await expression.promiseFoo()
        res.send(result)
    } catch (err) { 
        res.send(err)
    }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading