为什么我的 try/catch 在 node.js 中没有捕获到错误?

huangapple go评论90阅读模式
英文:

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

问题

我有一段带有try catch的代码块。在try块内,我使用了一个名为JSONata的JSON查询库。在某些情况下,当一个不希望的字符串错误地传递给该库时,该库会抛出一个错误。我的问题是,我的catch块没有被触发,应用程序只是崩溃了?

这里有一些伪代码来解释发生了什么。问题是当用户错误地将]放在id的末尾时,evaluate函数会抛出一个错误。我原本以为当错误被抛出时,我的catch块会捕获它并将错误消息发送给浏览器。但实际上我的应用程序只是崩溃了。

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)
}
英文:

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 = &lt;some JSON data here&gt;;
    let expression = jsonata(&quot;rows[userID=abc123]&#39;])&quot;
    expression.evaluate(data).then(result =&gt; {
        res.send(result)
    }    
}catch(err)
{ 
    res.send(err)
}

答案1

得分: 0

如Dave所提到的,你可以使用.catch

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

另外,如果你正在使用async/await,你可以这样做:

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)
    }
});
英文:

As Dave mentioned, you can use .catch

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

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

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

huangapple
  • 本文由 发表于 2023年5月25日 01:09:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76325932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定