Node.js 错误处理最佳实践使用 Promise 捕获错误123456789101112131415161718192021222324let 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 捕获错误12345678910111213141516171819202122let 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();