try. catch如果一个函数抛出错误NodeJS



我试图处理一个函数,如果它抛出一个错误:create.js

function Apple() {
createDB() //function that saves into db
}

createDB.js

function createDB() {
const Info = new collection(data)
Info.save()
}

假设createDB函数在数据库中不存在所需字段时抛出错误。我想处理这样的错误。

我试着:

function Apple() {
try{
createDB()//function that saves into db //if throws error go to catch 
block
} catch{
function that handles error
}
}

和我也试过:

function createDB() {
return new Promise((resolve, reject) => {
if some condition met{
const Info = new collection(data)
Info.save()
}else{
reject(error)
}
})    
}

但是它仍然没有进入catch块。我对这个话题比较陌生,所以任何建议都会很有帮助。基本上,如果函数抛出错误,我想处理错误,它应该去catch块。

您实际上没有遵循正确的语法。查看示例:

try {
nonExistentFunction();
} catch (error) {
console.error(error);
// expected output: ReferenceError: nonExistentFunction is not defined
// Note - error messages will vary depending on browser
}

使用try-catch更新的代码应该遵循上述语法:

function Apple() {
try{
createDB()//function that saves into db //if throws error go to catch 
block
} catch (error) {
function that handles error
// here you should log errors or use the logging lib
}
}

同样,如果你正在使用承诺,你可以遵循以下方法:

function createDB() {
return new Promise((resolve, reject) => {
if (condition) {
const Info = new collection(data);
Info.save().then(data =>{ resolve(data)})
.catch(e => {console.error(e)}) // handle this promise also
}
else {
reject(error);
} 
})    
}

同样,你需要理解什么时候使用try-catch块,什么时候使用promise。当代码是同步时,try、catch块用于处理异常(错误的一种类型)。你应该只在异步函数中使用promise,而不是其他。

使用下面的示例代码

在try块中,我们编写了我们想要执行的代码

如果发生任何错误控制器将进入catch块

在catch块中我们也收到错误

try {
//Here write your code which you want to execute
return true
} catch (error) {
//if there is an any error controller will come into this block and show error 
console.error(error);
return false

}

最新更新