我有一个node.js express app,我想抓住任何
<variable> is not defined
或
<object> does not have property <propertyname>
当我在本地运行项目并发生可编程错误时,我在控制台中收到这些消息并且请求被处理掉。我想在winston记录器中处理它们。
提前致谢
答案 0 :(得分:1)
从代码中删除依赖项并使用最少的可重现代码段进行测试似乎对我有用。
<强>更新强>
可以使用unhandledRejection
var express = require('express'),
path = require('path');
process.on('uncaughtException', function(err) {
console.log('uncaught exception', err);
}).on('unhandledRejection', (reason, p) => {
console.log('unhandledRejections reason', reason);
}).on('warning', (warning) => {
console.log(`warning, ... ${warning}`);
});
var app = express();
app.use('/api/subscriber', (req, res) => {
console.log('inside API');
return new Promise((resolve, reject)=>{
console.log(undeclaredVariable); // should error
res.status(200).send({
msg: 'hello world'
});
});
});
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(process.env.PORT || 5000); // Listen for requests
记录
inside API
unhandledRejections reason [ReferenceError: undeclaredVariable is not defined]