Node.js Try Catch 是一种错误处理机制。当期望一段代码抛出错误并被try包围时,可以在catch块中解决代码段中抛出的任何异常。如果未以任何方式处理错误,程序将突然终止,这不是一件好事。
注意:最好将Node.js Try Catch仅用于同步操作。我们还将在本教程中了解为什么不应该将Try Catch用于异步操作。
Node.js尝试捕获的示例
为什么不使用Node.js Try Catch来捕获异步操作中的错误
异步代码中的异常会怎样?
Node.js尝试捕获的示例
在此示例中,我们将在尝试同步读取文件的代码段周围使用Try Catch。
nodejs-try-catch-example.js
#example for Node.js Try Catch
var fs = require('fs');
try{
// 文件不存在
var data = fs.readFileSync('sample.html');
} catch (err){
console.log(err);
}
console.log("Continuing with other statements..");
当上述程序运行时..
终端输出
arjun@arjun-VPCEH26EN:~/nodejs$ node nodejs-try-catch-example.js
{ Error: ENOENT: no such file or directory, open 'sample.html'
at Object.fs.openSync (fs.js:652:18)
at Object.fs.readFileSync (fs.js:553:33)
at Object.<anonymous> (/nodejs/nodejs-try-catch-example.js:5:16)
at Module._compile (module.js:573:30)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Function.Module.runMain (module.js:609:10)
at startup (bootstrap_node.js:158:16)
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: 'sample.html' }
Continuing with other statements..
请注意,该程序并没有突然终止,而是继续执行后续语句。
现在,我们将看到如果不对上面的同一操作使用try catch,将会发生什么。
nodejs-try-catch-example-1.js
# error without Node.js Try Catch
var fs = require('fs');
// 尝试同步读取文件,而不是presenet文件
var data = fs.readFileSync('sample.html');
console.log("Continuing with other statements..");
代码中没有错误处理机制。并且该程序突然终止,并且随后的语句不执行。
当上述程序运行时..
终端输出
arjun@arjun-VPCEH26EN:~/nodejs$ node nodejs-try-catch-example-1.js
/home/arjun/nodejs/nodejs-try-catch-example-1.js:1
(function (exports, require, module, __filename, __dirname) { # example for Node.js Try Catch
^
SyntaxError: Invalid or unexpected token
at createScript (vm.js:74:10)
at Object.runInThisContext (vm.js:116:10)
at Module._compile (module.js:537:28)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Function.Module.runMain (module.js:609:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:598:3
为什么不使用Node.js Try Catch来捕获异步操作中的错误
考虑以下示例,在该示例中,我们尝试使用回调函数异步读取文件,并在出现问题时抛出错误。然后,我们用“尝试捕获”块围绕任务,希望能够捕获抛出的错误。
nodejs-try-catch-example-2.js
# Node.js Try Catch with Asynchronous Callback Function
var fs = require('fs');
try{
fs.readFile('sample.txta',
// 回调函数
function(err, data) {
if (err) throw err;
});
} catch(err){
console.log("In Catch Block")
console.log(err);
}
console.log("Next Statements")
终端输出
arjun@arjun-VPCEH26EN:~/nodejs/try-catch$ node nodejs-try-catch-example-2.js
Next Statements
/home/arjun/nodejs/try-catch/nodejs-try-catch-example-2.js:8
if (err) throw err;
^
Error: ENOENT: no such file or directory, open 'sample.txta'
如果您观察到输出,请进行控制台。在if(err) throw err之前已执行log(" Next Statements") ,这是因为,读取文件是异步完成的,并且控件不等待文件操作完成,而是继续执行next语句。这意味着控件不在try catch块内。如果在异步操作期间发生错误,则控件不会知道任何try catch块。因此,我们的Try Catch块无法捕获异步操作期间可能发生的错误,开发人员应避免使用Node.js Try Catch块捕获由异步任务引发的错误。
异步代码中的异常会怎样?
如果您对异步代码中的异常会发生什么感到困惑,这就是答案。如果您已通过Callback 回调函数并观察到错误对象作为参数,则在此处将所有错误或异常报告回给Node.js。
总结:
在本Node.js教程– Node.js Try Catch中,我们学习了使用Try Catch以及不使用Try Catch的场景。