NodeJS - 同步程式碼中的異常處理


異常是一種事件型別,發生在執行或執行程式時,該事件會停止程式正常流並返回系統。當異常發生時,方法建立一個物件並將其提供給執行時系統。這種建立異常並將其提供給執行時系統被稱為丟擲異常

我們需要處理這些異常來處理任何用例並防止系統崩潰或執行空前的指令集。如果我們不處理或丟擲異常,該程式可能會產生奇怪的行為。

同步程式中的異常處理

在這裡,我們將學習如何在程式的同步流中處理異常。同步程式流是指在收到請求後返回響應的流。

示例

// Define a divide program as a syncrhonous function
var divideNumber = function(x, y) {
   // 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
      return new Error("Can not divide by zero")
   } else {
      // No error occurred here, continue on
      return x/y
   }
}

// Divide 10 by 5
var result = divideNumber(10, 5)
// Checking if an Error occurs ?
if ( result instanceof Error ) {
   // Handling the error if it occurs...
   console.log("10/5=err", result)
}
else {
   // Returning the result if no error occurs
   console.log("10/5="+result)
}

// Divide 10 by 0
result = divideNumber(10, 0)
// Checking if an Error occurs ?
if ( result instanceof Error ) {
   // Handling the error if it occurs...
   console.log("10/0=err", result)
}
else {
   // Returning the result if no error occurs
   console.log("10/0="+result)
}

輸出

更新於:28-Apr-2021

144 次檢視

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告