Node.js 解释一些错误处理的方法
Node.js是一个开源的JavaScript运行环境。它经常用于服务器端构建Web和移动应用的API。许多公司如Netflix、PayPal、Uber等都使用Node.js。
预备知识:
- Promises(Promises)
- Async Await(异步等待)
错误是由程序根据诸多因素(如逻辑、语法、超时等)产生的任何问题。错误处理是Node.js中的一个重要部分,应当谨慎实施。在本教程中,让我们来看看一些处理错误的方法,但首先让我们设置我们的基本环境。
创建一个名为error.js的文件。该文件将作为探索各种方法的基础。
方法1:使用try-catch块。
catch块处理try块中代码引发的任何异常。
语法:
try{
// Code
}catch(error){
// Error Handling
}
示例:
try{
const areYouAwesome = false;
if(!areYouAwesome){
throw new Error("We know you are awesome,
we are having troubing with our code.")
}
}catch(error){
console.log(error.message);
}
输出:
We know you are awesome, we are having troubing with our code.
方法2:在执行异步操作时使用try-catch
在获取数据时,异步操作有时需要暂停程序。我们可以将异步等待函数与try-catch块配对以处理错误。
语法:
const myFunction = async () => {
try{
await operationWhichTakesTime()
}catch(error){
// Error handling
}
}
示例:
const delay = (wait) => {
return new Promise(resolve => setTimeout(resolve, wait));
}
const awesomeFunction = async () => {
try{
await delay(2000)
throw new Error("Error thrown after delay");
}catch(error){
console.log(error.message);
}
}
awesomeFunction();
输出:
Error thrown after delay
方法3:使用Promise
Promise用于处理JavaScript中的异步操作。Promise有三个状态,即等待状态、已解决状态和已拒绝状态。在等待状态下,Promise正在等待其他函数或获取某些数据。在已解决状态下,函数按预期工作,Promise已解决。在已拒绝状态下,函数出现了一些错误,Promise被拒绝。
语法:
promise().then((data) => {
// Code
}).catch((error) => {
// Error handler
})
示例:
const awesomeFunction = (isAwesome) => {
return new Promise((resolve, reject) => {
if(isAwesome){
resolve("You are awesome");
}else{
reject("We know you are awesome,
we are having troubing with our code.")
}
})
}
awesomeFunction(false).then((message) => {
console.log(message);
}).catch((error) => {
console.log(error)
});
输出:
We know you are awesome, we are having troubing with our code.
方法4:使用事件监听器
Node.js中的进程全局对象可以用来监听程序中可能出现的任何未捕获的异常。
语法:
process.on('uncaughtException', error => {
// Error Handling
process.exit(1)
})
示例:
process.on('uncaughtException', error => {
console.log(error.message);
process.exit(1)
})
const awesomeFunction = (isAwesome) => {
if(!isAwesome){
throw new Error("We know you are awesome,
we are having troubing with our code.")
}
}
awesomeFunction();
输出:
We know you are awesome, we are having troubing with our code.