NodeJS - 非同步程式碼中的異常處理
異常是指在執行或執行程式時發生的事件型別,會停止程式的正常流程並返回系統。當異常發生時,該方法將建立一個物件並將其提供給執行時系統。這種建立異常並將其提供給執行時系統被稱為丟擲異常。
我們需要處理這些異常來處理任何用例並防止系統崩潰或執行一組空前的指令。如果我們不處理或丟擲異常,程式的執行可能會很奇怪。
非同步程式中的異常處理
在這裡,我們將學習如何在程式的非同步流程中處理異常。非同步程式碼也稱為基於回撥的程式碼。它基本上給出了一個臨時響應,說明已收到請求或正在進行狀態以說明其進一步的工作情況。處理完成後,它將使用最終響應將回調反饋給所需系統。
回撥有一個名為err的引數。如果在計算期間發生任何錯誤,此引數將儲存錯誤,否則 err 將為空。
示例
// Define a divide program as a syncrhonous function var divideNumber = function(x, y, next) { // if error condition? if ( y === 0 ) { // Will "throw" an error safely by returning it // If we donot throw an error here, it will throw an exception next(new Error("Can not divide by zero")) } else { // If noo error occurred, returning error as null next(null, x/y) } } // Divide 10 by 5 divideNumber(10, 5, function(err, result) { if (err) { // Handling the error if it occurs... console.log("10/5=err", err) } else { // Returning the result if no error occurs console.log("10/5="+result) } }) // Divide 10 by 0 divideNumber(10, 0, function(err, result) { // Checking if an Error occurs ? if (err) { // Handling the error if it occurs... console.log("10/0=err", err) } else { // Returning the result if no error occurs console.log("10/0="+result) } })
輸出
廣告