← 中文资源

简体中文版本

定时器回调逃出 try catch

setTimeout 里的 throw 发生时调用栈早已返回,try catch 永远接不住:这类错误只能交给 uncaughtException 处理器兜底。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

try block finished without catching anything
process handler caught: boom inside timer

实现说明

定时器回调逃出 try catch可以归结为函数 scheduleFlakyWork。 Error 前面没有校验门槛——那一行一执行,raise 就发生。

使用要点

  • 跑完文件,输出里会留下标记——try block finished without catching anything。

常见问题

代码会拦截坏输入吗?

这个示例不校验输入。Error 在 throw 位置无条件抛出——没有任何东西守着它。

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 文件在加载时定义 scheduleFlakyWork。

签名一览:function scheduleFlakyWork()

核心语句

process.on('uncaughtException', (err) => {
  console.log(`process handler caught: ${err.message}`);
});
throw new Error('boom inside timer');

代码示例

// Install the safety net first — it is the only handler that can
// observe a throw from a timer callback
process.on('uncaughtException', (err) => {
  console.log(`process handler caught: ${err.message}`);
});

function scheduleFlakyWork() {
  // This throw happens long after the calling stack returned
  setTimeout(() => {
    throw new Error('boom inside timer');
  }, 20);
}

try {
  scheduleFlakyWork();
  console.log('try block finished without catching anything');
} catch {
  // Unreachable: timer callbacks escape try catch blocks because the
  // stack that ran the try block is gone by the time they fire
  console.log('catch reached');
}