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)
}

>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)
    }
});

Leave a Reply