Node.js中Winston无法记录unhandledRejection至日志文件求解
解决Node.js中Winston记录unhandledRejection错误的问题
问题根源
unhandledRejection事件的第一个参数reason可能是Promise对象或Error实例,直接用logger.info(reason)会将Promise转为[object Promise],丢失错误详情。- 原回调不是async函数,直接使用
await会触发语法错误。
正确实现方式
将unhandledRejection的回调定义为async函数,先解析可能的Promise类型reason,再用Winston记录完整错误信息:
const winston = require('winston'); // 配置Winston logger const logger = winston.createLogger({ level: 'info', format: winston.format.combine( winston.format.timestamp(), winston.format.json() ), transports: [ new winston.transports.File({ filename: 'error.log', level: 'error' }), new winston.transports.File({ filename: 'combined.log' }) ] }); // 处理unhandledRejection事件 process.on('unhandledRejection', async (reason, promise) => { // 解析可能的Promise类型reason const error = await reason.catch(err => err); // 记录完整错误信息,包括stack logger.error('Unhandled Rejection occurred', { error: error instanceof Error ? error.stack : error, promise: promise.toString() }); // 可选:退出进程(根据业务需求决定) process.exit(1); });
关键说明
- 用
async修饰回调函数,允许内部使用await解析Promise类型的reason。 - 通过
reason.catch(err => err)确保无论reason是已拒绝的Promise还是直接的错误对象,都能拿到实际错误内容。 - Winston的
logger.error支持传入元数据对象,将错误栈(error.stack)存入日志,方便排查问题。 - 如果不需要退出进程,可以去掉
process.exit(1),但生产环境建议处理后退出,避免程序处于不稳定状态。
内容的提问来源于stack exchange,提问作者Tsar Buig
相关产品推荐
相关产品推荐

