Node.js 错误处理最佳实践

使用 Promise 捕获错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
let func = function (n) {
return new Promise((resolve, reject) => {
resolve(n * n);
});
};
func(2)
.then((res) => {
console.log(res);
return func(res);
})
.then((res) => {
console.log(res);
throw new Error("Error");
})
.then((res) => {
console.log(res);
return func(res);
})
.catch((err) => {
console.log(err);
})
.finally(() => {
console.log("结束");
});

使用 async/await 捕获错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let func = function (n) {
return new Promise((resolve, reject) => {
resolve(n * n);
});
};
async function asyncTask() {
try {
const valueA = await func(2);
console.log(valueA);
const valueB = await func(valueA);
console.log(valueB);
throw new Error("Error");
const valueC = await func(valueB);
console.log(valueC);
return valueC;
} catch (err) {
console.log(err);
} finally {
console.log("结束");
}
}
asyncTask();