[英]Error handling in ExpressJS
我想在我的expressJS應用程序中單點開發錯誤處理。
我在expressJS配置中添加了以下代碼:
app.use(app.router);
app.use(function (err, req, res, next) {
console.error('ExpressJS : error!!!');
});
因此,應用程序中發生的任何錯誤都將被執行,因此我可以以自定義方式處理錯誤。
但是,上述功能無法在javascript錯誤或以下代碼上執行:
throw new Error('something broke!');
我讀過了 :
http://expressjs.com/guide/error-handling.html和
http://derickbailey.com/2014/09/06/proper-error-handling-in-expressjs-route-handlers/
但是,仍然無法在我的expressJS應用程序中進行常規錯誤處理。
誰能解釋我將如何處理任何應用程序錯誤?
不是通過快遞,而是nodejs,您可以嘗試
process.on('uncaughtException', function(err) {
console.log(err);
});
由於“ throw”是javascript,因此不受expressjs的控制。
對於那些錯誤,例如快速路由,您應該能夠捕獲到app.error或app.use(function(err ..,正如其他建議那樣,也可以使用req,res對象。
app.error(function(err, req, res, next){
//check error information and respond accordingly
});
//newer versions
app.use(function(err, req, res, next) {
});
實際上,您需要將錯誤處理放在路由器的末端,
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
如果您有錯誤記錄器,則必須將其放在錯誤處理的前面。
app.use(bodyParser());
app.use(methodOverride());
app.use(logErrors); // log the error
app.use(clientErrorHandler); // catch the client error , maybe part of the router
app.use(errorHandler); // catch the error occured in the whole router
並且您可以定義幾個錯誤處理中間件,每個錯誤處理捕獲不同級別的error。
在Express中,您可以通過使用參數調用next()
觸發路由錯誤處理,如下所示:
app.get('/api/resource',function(req, res, next) {
//some code, then err occurs
next(err);
})
調用next()
將觸發鏈中的下一個中間件/處理程序。 如果將參數傳遞給它(如next(err)
),則它將跳過下一個處理程序並觸發錯誤處理中間件。
據我所知,如果您只是throw
一個錯誤,它不會被express捕獲,並且可能會使您的節點實例崩潰。
請記住,您可以根據需要設置任意數量的錯誤處理程序:
app.use(function (err, req, res, next) {
//do some processing...
//let's say you want more error middleware to trigger, then keep on calling next with a parameter
next(err);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.