eslint可通过@typescript-eslint/no-floating-promises规则静态捕获未处理的await,配合ci强制校验、运行时unhandledrejection监听及团队规范,实现异步错误防控闭环。

不能强行拦截裸露 await,因为 JavaScript/TypeScript 语法本身不禁止它,且运行时也无法在执行前“拦截”未包裹的 await 行为。真正可行的是:在代码进入 CI 流水线前,用静态检查工具识别并阻断不符合异常处理规范的异步调用。
用 ESLint 规则捕获无错误处理的 await
核心是启用 @typescript-eslint/no-floating-promises(TS)或 no-promise-executor-return + 自定义规则(JS),但更推荐前者——它能检测所有未被 try/catch、.catch()、await 上层兜底或显式 void 声明的 Promise 使用。
- 安装插件:
npm install --save-dev @typescript-eslint/eslint-plugin @typescript-eslint/parser - 在
.eslintrc.js中启用:rules: { '@typescript-eslint/no-floating-promises': ['error', { ignoreVoid: true }] } - 配合
eslint --fix自动插入void(仅用于明确放弃错误处理的场景,如日志上报)
CI 流水线中强制校验并失败构建
将 ESLint 集成进 lint 阶段,任何违规代码直接导致 job 退出非零码,中断后续流程。
- GitLab CI 示例:
lint: stage: lint script: - npm ci --no-audit --no-fund - npx eslint src/**/*.{ts,js} --ext .ts,.js --max-warnings 0 - GitHub Actions 示例:
- name: Run ESLint run: npx eslint src/ --ext .ts,.js --max-warnings 0
-
--max-warnings 0确保警告也被视为错误,避免“仅提示不阻断”
补充防御:禁止隐式顶层 await 和未处理 rejection
ESLint 只管语法层面,还需运行时兜底防止漏网之鱼。
- 在入口文件(如
main.ts)顶部统一监听:process.on('unhandledRejection', (reason) => { console.error('Unhandled promise rejection:', reason); process.exit(1); }); - CI 中启动服务前加健康检查脚本,验证该监听器是否生效
- 禁用顶层
await(Node.js 14.8+ 支持):在package.json中设"type": "module"后,顶层 await 仅限 ES 模块入口;通过限制入口类型间接管控
团队协作配套措施
规则生效依赖一致的开发环境和认知对齐。
- 编辑器自动提示:VS Code 安装 ESLint 插件,实时标红裸 await
- 提交前钩子(pre-commit):用
husky + lint-staged拦截本地未修复问题 - 文档明确规范:定义哪些场景允许
void await xxx()(如非关键埋点),哪些必须try/catch(如 API 调用、DB 操作)











