跳轉到

2.3 錯誤處理與 Debugging#

同步與非同步的錯誤處理#

同步程式碼:try/catch#

try {
  const data = JSON.parse("不是合法的JSON");   // 會 throw
} catch (err) {
  console.error("解析失敗:", err.message);
}

async/await:一樣用 try/catch#

async function loadData() {
  try {
    const res = await fetch(url);
    return await res.json();
  } catch (err) {
    console.error("載入失敗:", err.message);
    throw err;   // 視需求決定要不要繼續往上拋
  }
}

原則:錯誤要嘛處理掉,要嘛往上拋,不要默默吞掉。空的 catch {} 是除錯時最討厭的東西——錯誤消失了卻不知道發生過。

自訂錯誤與拋出#

function divide(a, b) {
  if (b === 0) {
    throw new Error("除數不可為 0");
  }
  return a / b;
}

Debugging 三招#

第一招:console 輸出(最快速)#

console.log("這裡的 user 是:", user);
console.table(items);          // 陣列/物件用表格看
console.log(JSON.stringify(obj, null, 2));   // 深層物件

第二招:node --inspect(正式除錯器)#

node --inspect-brk app.js

然後打開 Chrome 的 chrome://inspect,可以設中斷點、單步執行、看變數。VS Code 使用者直接在程式碼行號旁點紅點設中斷點,按 F5 啟動偵錯更方便。

第三招:看 stack trace#

程式崩潰時 Node 會印出錯誤堆疊:

TypeError: Cannot read properties of undefined (reading 'name')
    at main (/path/app.js:10:25)
    at process.processTicksAndRejections (...)

從最上面第一行開始讀:錯誤類型(TypeError)、訊息(reading 'name')、以及出錯的檔案與行號(app.js:10:25)——直接跳到那行看。

程式崩潰的常見原因#

錯誤訊息 原因
Cannot read properties of undefined 存取了不存在物件的屬性
is not a function 名字打錯,或 import 的東西不對
MODULE_NOT_FOUND require/import 的路徑或套件名錯了
EADDRINUSE port 已被占用(舊程序沒關)