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)
}
})输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP