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 次查看

开启你的 职业生涯

完成课程,获得认证

开始
广告
© . All rights reserved.