Skip to content

空 catch 静默吞掉错误

快速摘要

你写了 catch (e) {} 却无日志或处理——失败被静默吞掉,bug 在远离源头处才显现。

为什么发生

  • 为让 linter 闭嘴而加空 catch

  • 捕获过宽(catch (e) {})而非特定错误类型

  • catch 中忘了记录、重新抛出或设置回退值

最小示例

✗ 错误代码
function parseConfig(raw) {
  try {
    return JSON.parse(raw);
  } catch (e) {} // silent — caller gets undefined
}
const cfg = parseConfig('bad');
console.log(cfg.port); // TypeError: Cannot read properties of undefined
✓ 修复代码
function parseConfig(raw) {
  try {
    return JSON.parse(raw);
  } catch (e) {
    console.error('Failed to parse config:', e.message);
    return {};
  }
}
const cfg = parseConfig('bad');
console.log(cfg.port); // undefined — safe default

空 catch 吞掉 JSON 错误并返回 undefined,调用者稍后崩溃。记录错误并返回安全默认值可使失败可见且下游代码安全。

如何诊断

  • 搜索空 catch 块:/catch\s*\([^)]*\)\s*\{\s*\}/

  • 在每个 catch 中加 console.error 重新运行以暴露隐藏失败

  • 检查周围代码是否假定 try 总是成功

如何修复

  • 记录带足够上下文的错误以便诊断

  • 若此层无法处理则重新抛出

  • 只捕获你能实际恢复的特定错误类型

如何预防

  • 启用禁止空 catch 块的 linter 规则(no-empty)

  • 即便原型阶段也至少在 catch 中记录错误

相关资源

相关术语

相关课程

← 返回语言