为什么错误处理在 Node.js 中如此重要
Node.js 的非阻塞 I/O 模型让高并发成为可能,但也让错误处理变得复杂。一个未捕获的异常可能导致进程崩溃,而异步操作中的错误若未妥善处理,往往会被静默吞掉,给调试带来巨大困难。
许多开发者习惯用 try...catch 包裹所有代码,但在异步场景下这并不总是有效。本文将带你从基础到进阶,掌握 Node.js 错误处理的最佳实践,并给出可直接运行的示例。
1. 错误处理的基本模式
1.1 回调函数中的错误优先约定
Node.js 早期广泛使用回调函数,约定错误作为第一个参数返回:
const fs = require('fs');
fs.readFile('/etc/passwd', (err, data) => {
if (err) {
console.error('读取文件失败:', err);
return;
}
console.log(data.toString());
});
注意:务必在回调中检查 err,否则错误会被忽略。同时避免在回调中抛出异常,因为这会中断事件循环。
1.2 使用 Promise 处理异步错误
Promise 提供了 .catch() 方法来集中处理错误:
const fs = require('fs').promises;
fs.readFile('/etc/passwd')
.then(data => console.log(data.toString()))
.catch(err => console.error('读取失败:', err));
💡 提示:在 Promise 链中,错误会沿着链向后传递,只需在末尾添加一个 .catch() 即可捕获前面所有环节的错误。
1.3 async/await 与 try…catch
async/await 让异步代码看起来像同步代码,可以配合 try...catch 使用:
async function readFile() {
try {
const data = await fs.readFile('/etc/passwd');
console.log(data.toString());
} catch (err) {
console.error('读取失败:', err);
}
}
注意:try...catch 只能捕获 await 表达式中的错误。如果忘记 await,错误将不会被捕获。
2. 集中式错误处理
2.1 创建自定义错误类
定义业务错误类,便于区分错误类型:
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
this.isOperational = true; // 标记为可预见的操作错误
Error.captureStackTrace(this, this.constructor);
}
}
// 使用
throw new AppError('用户不存在', 404);
2.2 Express 中的错误处理中间件
在 Express 中,使用四个参数的中间件来捕获所有错误:
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;
res.status(statusCode).json({
status: 'error',
message: err.message || '服务器内部错误'
});
});
💡 提示:错误处理中间件必须放在所有路由之后,且必须包含四个参数,否则 Express 无法识别。
2.3 使用 async 包装器避免重复 try…catch
每个路由都写 try...catch 太繁琐,可以封装一个高阶函数:
const asyncHandler = fn => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
// 使用
app.get('/user/:id', asyncHandler(async (req, res) => {
const user = await User.findById(req.params.id);
if (!user) throw new AppError('用户不存在', 404);
res.json(user);
}));
这样,所有异步错误都会自动传递给错误处理中间件。
3. 全局错误捕获与进程管理
3.1 监听未捕获的异常
即使有完善的错误处理,仍可能有漏网之鱼。监听 uncaughtException 和 unhandledRejection 事件:
process.on('uncaughtException', (err) => {
console.error('未捕获的异常:', err);
// 记录日志并优雅退出
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('未处理的 Promise 拒绝:', reason);
// 建议记录并退出,避免未知状态
});
注意:uncaughtException 后进程状态可能不可靠,最佳实践是记录错误后退出,由进程管理器(如 PM2)重启。
3.2 使用 domain 模块?不推荐!
domain 模块已被废弃,不要在新项目中使用。推荐使用 async_hooks 或 AsyncLocalStorage 进行请求级别的上下文追踪。
4. 实战:构建一个健壮的 API 服务
让我们结合以上知识点,创建一个简单的用户管理 API。
4.1 项目结构
project/
├── app.js
├── errors/
│ └── AppError.js
├── routes/
│ └── users.js
└── package.json
4.2 安装依赖
npm init -y
npm install express
4.3 定义错误类和中间件
// errors/AppError.js
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = AppError;
4.4 创建路由
// routes/users.js
const express = require('express');
const AppError = require('../errors/AppError');
const router = express.Router();
const users = [{ id: 1, name: 'Alice' }];
router.get('/:id', asyncHandler(async (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) throw new AppError('用户不存在', 404);
res.json(user);
}));
// asyncHandler 定义
function asyncHandler(fn) {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
}
module.exports = router;
4.5 主应用文件
// app.js
const express = require('express');
const usersRouter = require('./routes/users');
const AppError = require('./errors/AppError');
const app = express();
app.use('/users', usersRouter);
// 404 处理
app.use((req, res, next) => {
next(new AppError('接口不存在', 404));
});
// 全局错误处理
app.use((err, req, res, next) => {
if (err.isOperational) {
res.status(err.statusCode).json({ message: err.message });
} else {
console.error('非操作错误:', err);
res.status(500).json({ message: '服务器内部错误' });
}
});
const PORT = 3000;
app.listen(PORT, () => console.log(`服务运行在 http://localhost:${PORT}`));
4.6 测试
启动服务后,访问 http://localhost:3000/users/1 应返回用户信息,访问 http://localhost:3000/users/999 应返回 404 错误。
5. 常见坑与最佳实践总结
- 始终处理 Promise 拒绝:使用
.catch()或try...catch,避免unhandledRejection。 - 区分操作错误与程序错误:操作错误(如验证失败)应返回给客户端,程序错误(如数据库连接失败)应记录并重启。
- 不要吞掉错误:即使记录日志,也要考虑是否应该向上传递。
- 使用错误码:返回给客户端的错误信息应包含可读的消息和错误码,便于前端处理。
- 日志记录:使用 Winston 或 Pino 等日志库,结构化记录错误信息。
- 生产环境隐藏堆栈:不要将错误堆栈返回给客户端,防止信息泄露。
6. 延伸阅读
- Node.js 官方文档:错误处理
- Express 错误处理指南
- 使用 AsyncLocalStorage 进行请求追踪
通过本文的实践,你应该能够构建出健壮的 Node.js 应用,从容应对各种错误场景。记住,好的错误处理不是事后补救,而是设计的一部分。