英文:
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 = <some JSON data here>;
let expression = jsonata("rows[userID=abc123]'])"
expression.evaluate(data).then(result => {
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 => {
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)
}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论