2017-04-03 94 views
0

我有節點7.8.0,我已閱讀Node.js Best Practice Exception Handling如何設置Node.js錯誤處理?

仍然我似乎無法理解node.js中的錯誤處理。

對於我http我有

server.on('error',() => console.log('Here I should be replacing 
the Error console.')); 

對於404我有這樣的代碼

app.use((req, res, next) => { 
    let err = new Error('Not Found'); 
    err.status = 404; 
    next(err); 
}); 
app.use((err, req, res) => { 
    res.status(err.status); 
    res.render('error'); 
}); 

404被抓住了,它創建了錯誤的對象,然後它通過渲染錯誤觀點正確的處理我想要。但它也會向我的控制檯拋出錯誤日誌,我不知道該從哪裏來,以及如何阻止它。

我想使用自己的錯誤處理,並且從來沒有像404一樣的錯誤寫入控制檯。

我試過的代碼似乎並不奏效。

var server = http.createServer(app); 
const onError =() => console.log('Here I should be replacing the Error console.'); 
server.on('error', onError); 
server.on('uncaughtException', onError); 
process.on('uncaughtException', onError); 

回答

0

我不確定它如何渲染錯誤視圖,因爲錯誤處理程序只需要4個參數,而只傳遞3個參數。這就是Express如何區分錯誤處理程序和正常路徑處理程序(記錄在文件here)。

試試這個:

app.use((err, req, res, next) => { 
    res.status(err.status); 
    res.render('error'); 
}); 
0

這是由於expressjs。 Expressjs如果env不等於測試,則所有錯誤將寫入控制檯。

function logerror(err) { 
    if (this.get('env') !== 'test') console.error(err.stack || err.toString()); 
} 

而且http.Server沒有事件命名爲錯誤

+0

你是對的,如果我設置的環境中測試它的工作原理。但是如果我將其設置爲生產,它仍然會將錯誤發送給控制檯。有沒有辦法讓我不能爲任何環境芽的發展做到這一點? – Ragnar