處理變量未定義的錯誤我有一個明確的Node.js應用程序,和我想捕捉任何node.js中通過中間件
<variable> is not defined
或
<object> does not have property <propertyname>
當我在本地運行項目,併發生可編程錯誤我在控制檯中獲取這些消息,請求被處置。我想在winston記錄器中處理它們。
在此先感謝
處理變量未定義的錯誤我有一個明確的Node.js應用程序,和我想捕捉任何node.js中通過中間件
<variable> is not defined
或
<object> does not have property <propertyname>
當我在本地運行項目,併發生可編程錯誤我在控制檯中獲取這些消息,請求被處置。我想在winston記錄器中處理它們。
在此先感謝
從您的代碼中刪除依賴關係,並以最小的可重複的測試片段似乎爲我工作。
更新
未處理的拒絕可以用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
如果你想避免'不defined`錯誤它記錄
inside API
unhandledRejections reason [ReferenceError: undeclaredVariable is not defined]
,你需要使用代碼絨毛等處理eslint。但是我很想知道,爲什麼要在運行時記錄它,而不是在早期修復它? – Sridhar
它不是語法錯誤,它更像是從數據庫收到的對象沒有預期的屬性。所以它是運行時錯誤。例如除零 – melgamal
你有沒有考慮過快遞的默認[錯誤處理中間件](http://expressjs.com/en/guide/using-middleware.html#middleware.error-handling)捕捉這樣的錯誤 – Sridhar