Node.js Try Catch 是一種錯(cuò)誤處理機(jī)制。當(dāng)期望一段代碼拋出錯(cuò)誤并被try包圍時(shí),可以在catch塊中解決代碼段中拋出的任何異常。如果未以任何方式處理錯(cuò)誤,程序?qū)⑼蝗唤K止,這不是一件好事。
注意:最好將Node.js Try Catch僅用于同步操作。我們還將在本教程中了解為什么不應(yīng)該將Try Catch用于異步操作。
Node.js嘗試捕獲的示例
為什么不使用Node.js Try Catch來(lái)捕獲異步操作中的錯(cuò)誤
異步代碼中的異常會(huì)怎樣?
在此示例中,我們將在嘗試同步讀取文件的代碼段周圍使用Try Catch。
#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..");
當(dāng)上述程序運(yùn)行時(shí)..
終端輸出
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..
請(qǐng)注意,該程序并沒(méi)有突然終止,而是繼續(xù)執(zhí)行后續(xù)語(yǔ)句。
現(xiàn)在,我們將看到如果不對(duì)上面的同一操作使用try catch,將會(huì)發(fā)生什么。
# error without Node.js Try Catch var fs = require('fs'); // 嘗試同步讀取文件,而不是presenet文件 var data = fs.readFileSync('sample.html'); console.log("Continuing with other statements..");
代碼中沒(méi)有錯(cuò)誤處理機(jī)制。并且該程序突然終止,并且隨后的語(yǔ)句不執(zhí)行。
當(dāng)上述程序運(yùn)行時(shí)..
終端輸出
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
考慮以下示例,在該示例中,我們嘗試使用回調(diào)函數(shù)異步讀取文件,并在出現(xiàn)問(wèn)題時(shí)拋出錯(cuò)誤。然后,我們用“嘗試捕獲”塊圍繞任務(wù),希望能夠捕獲拋出的錯(cuò)誤。
# Node.js Try Catch with Asynchronous Callback Function var fs = require('fs'); try{ fs.readFile('sample.txta', // 回調(diào)函數(shù) 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'
如果您觀察到輸出,請(qǐng)進(jìn)行控制臺(tái)。在if(err) throw err之前已執(zhí)行log(" Next Statements") ,這是因?yàn)椋x取文件是異步完成的,并且控件不等待文件操作完成,而是繼續(xù)執(zhí)行next語(yǔ)句。這意味著控件不在try catch塊內(nèi)。如果在異步操作期間發(fā)生錯(cuò)誤,則控件不會(huì)知道任何try catch塊。因此,我們的Try Catch塊無(wú)法捕獲異步操作期間可能發(fā)生的錯(cuò)誤,開(kāi)發(fā)人員應(yīng)避免使用Node.js Try Catch塊捕獲由異步任務(wù)引發(fā)的錯(cuò)誤。
如果您對(duì)異步代碼中的異常會(huì)發(fā)生什么感到困惑,這就是答案。如果您已通過(guò)Callback 回調(diào)函數(shù)并觀察到錯(cuò)誤對(duì)象作為參數(shù),則在此處將所有錯(cuò)誤或異常報(bào)告回給Node.js。
在本Node.js教程– Node.js Try Catch中,我們學(xué)習(xí)了使用Try Catch以及不使用Try Catch的場(chǎng)景。