解析 Node.js 错误日志通常包含定位错误来源、理解错误类型、复现问题、修复与预防几个步骤。下面从“看日志 → 懂错误 → 用工具 → 实战技巧”系统讲一下。
一个典型的 Node.js 错误日志通常包含:
Error: Cannot find module 'express'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
at Function.Module._load (internal/modules/cjs/loader.js:728:27)
at Module.require (internal/modules/cjs/loader.js:1005:19)
at Object.<anonymous> (/app/index.js:1:17)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
Error / TypeError / RangeErrorCannot find module 'express'| 错误类型 | 含义 | 常见原因 |
|---|---|---|
Error |
通用错误 | 抛出的异常 |
TypeError |
类型错误 | undefined.xxx |
ReferenceError |
变量未定义 | 拼写错误 |
SyntaxError |
语法错误 | 代码写错 |
RangeError |
越界 | 递归过深 |
ECONNREFUSED |
连接失败 | 服务没起 |
ETIMEDOUT |
超时 | 网络问题 |
at Object.<anonymous> (/src/user.js:12:5)
at Module._compile (internal/modules/cjs/loader.js:...)
含义:
/src/user.js✅ 第一步永远看:
logger.error({
message: err.message,
stack: err.stack,
userId: req.user?.id
})
工具:
winstonpinobunyanprocess.on('uncaughtException', err => {
console.error('未捕获异常', err)
})
process.on('unhandledRejection', err => {
console.error('未处理 Promise', err)
})
node --stack-trace-limit=100 app.js
日志:
TypeError: Cannot read property 'name' of undefined
at getUser (/user.js:20:10)
✅ 分析:
/user.js 第 20 行user.nameuser 是 undefined✅ 修复:
if (!user) return res.status(404).json({ msg: '用户不存在' })
✅ 不要吞掉错误
catch (e) { /* 空 */ } ❌
✅ 抛错带上下文
throw new Error(`用户查询失败 userId=${id}`)
✅ 使用 Error.cause(Node 16+)
throw new Error('DB error', { cause: err })
你可以:
我可以直接帮你逐行解析并给修复方案。