错误类型与处理
system/user/assertion errors。
30 分钟
错误类型与处理
Node 把错误分为 系统错误、用户代码错误、断言失败 等类别。CLI 与 npm 包要在 退出码、stderr、Promise rejection 上行为一致——否则脚本进 CI 时难以判断失败原因。
学习目标
- 区分 system / user / assertion 类错误
- 在 async 与 EventEmitter 中统一错误传播
- 衔接 node-errors 与 testing-essentials
错误从哪来
| 类型 | 典型来源 | 处理倾向 |
|---|---|---|
| System | ENOENT、网络超时、EACCES | 记录、重试或向上抛 |
| User | 非法参数、业务规则拒绝 | 友好 message、退出码 1 |
| Assertion | assert()、测试断言 | 开发期暴露,生产慎用 |
import fs from "node:fs/promises";
try {
await fs.readFile("missing.txt");
} catch (err) {
if (err.code === "ENOENT") {
console.error("文件不存在:", err.path);
process.exitCode = 1;
} else {
throw err; // 未知系统错误继续抛
}
}
同步、Promise 与 uncaughtException
- 同步:try/catch
- Promise:
.catch()或顶层await+ try/catch - EventEmitter:
'error'事件(见 nva-events)
process.on("unhandledRejection", (reason) => {
console.error("Unhandled rejection:", reason);
process.exitCode = 1;
});
CLI 入口建议在 最外层 捕获 rejection,打印 stderr 后以非零退出——与 nva-cli 的 main() 包装一致。
自定义错误类
export class UserError extends Error {
constructor(message) {
super(message);
this.name = "UserError";
}
}
export function isUserError(err) {
return err instanceof UserError;
}
Nest 的 HttpException 是框架层封装(nest-exceptions);包与脚本用 plain Error 子类 即可,便于 test-intro 中断言 。