node.js - 在 NodeJS / Express / React 堆栈中记录错误
问题描述
我一直在使用 React、NodeJS/Express 开发应用程序。我的问题是当错误出现在后端 API 服务器上时,如何记录错误(在节点控制台或外部文件中)?
例如,假设我有一个 api 端点“/api/example”,它将从数据库中获取数据并处理数据。在那个过程中,我有一个数据库类
class DB {
update(sql) {
...
}
...
}
但是当我调用该方法时,我打错了,所以我调用db.updates(sql)
了,控制台不会显示任何错误Uncaught error: db.updates is not a function
,并且请求只会挂起,直到它终止。
所以我的问题是如何让错误出现在控制台上?它越来越烦人,因为这比它应该消耗的时间多得多。
我尝试了摩根,它似乎只是记录了 http 请求?我也尝试了winston,但在日志文件或控制台中仍然看不到任何内容(尽管我不确定如何使用它。我已在最底部附加了我的winston 记录器代码)。
我以前没有遇到过这个问题,因为我之前一直使用像 ejs 这样的模板视图引擎,当发生这样的错误时,ejs 页面将呈现错误。现在有了 react 环境和只发送 json 响应的 API 服务器,页面就会进入组件的加载状态,直到 fetch 请求失败。
任何指针将不胜感激。谢谢你。
温斯顿 logger.js
import winston from 'winston'
const options = {
file: {
level: 'error',
filename: `./logs/error.log`,
handleExceptions: true,
json: true,
colorize: false,
},
console: {
level: 'error',
handleExceptions: true,
json: false,
colorize: true,
},
};
let logger = winston.createLogger({
transports: [
new winston.transports.File(options.file),
new winston.transports.Console(options.console)
],
exitOnError: true,
});
logger.stream = {
write: function (message, encoding) {
transports (file and console)
logger.info(message);
},
};
export default logger
应用程序.js
import logger from './logger'
import morgan from 'morgan'
...
app.use( morgan('combined', {stream: logger.stream}) )
...
解决方案
在我的项目中,我们在路线中遇到错误(try/catch):
router.get('/', function(req, res, next) {
try {
//get the data
res.status(200).json(data);
} catch (error) {
next(error);
}
});
并在 app.js 中管理答案:
app.use(function (err, req, res, next) {
//TODO implement error log (e.g. WINSTON)
res.status(errorStatus).json({"status": err.status, "data": err.data, "message": err.message});
});
推荐阅读
- ruby - 从迭代器调用迭代器,绑定一个参数
- swift - 子类如何覆盖 Swift 中父类的属性?
- c# - C# 捕获基本自定义异常
- postgresql - Docker Postgres - 创建数据库和用户时出错
- html - 在html页面中插入图片
- javascript - axios 可以配置为使用 HTTP/1.1 吗?
- java - 如何配置 Jackson 和 Spring 以根据 URL 路径和嵌套级别以不同方式呈现对象
- scala - Kryo setWarnUnregisteredClasses 为 true,在 spark 配置中不显示任何内容
- spring-boot - 如果我在 spring-boot 中以服务级别提供 @Async 将不起作用
- ios - Diffable Snapshot 重新加载节标题