[英]How to handle errors in Node.js/express
我試圖捕獲錯誤而不是拋出錯誤。 我嘗試了try / catch,但意識到這沒用,所以即時通訊有點松懈。 這兩個錯誤是與mongodb相關的,但是我認為仍然會拋出節點/表達錯誤。
app.get( "/test/:lastName", function ( reqt, resp ) {
var driverName = reqt.params.lastName
mongoClient.connect( "mongodb://localhost/enteprise",
function( err, db ) {
if ( err ) {
console.error("1 mess " + err)
}
var database = db.db( "enteprise" )
var collection = database.collection( "driversCol" )
collection.findOne( { lastName : driverName },
function( err, res ) {
if ( err ) {
console.error("2 mess " + err)
}
resp.json( res.rate )
db.close()
})
})
})
案例
如果我curl -X GET localhost:3000/test/Owen
那么應該返回“ 43”作為多數民眾贊成的比率。
當前,如果我curl -X GET localhost:3000/test/Cressey
它將拋出類型錯誤,因為它不在數據庫中。
給定上面的代碼和示例,如何捕獲錯誤?
首先,我認為您應該使用next()
來發回在回調中遇到的錯誤:
app.get( "/test/:lastName", function ( req, resp, next ) {
// some code...
if ( err ) {
return next("1 mess " + err)
}
關於TypeError,它的發生是因為在沒有任何結果的情況undefined
從MongoDB中獲得undefined
的信息,但這不是錯誤,因此不會輸入if
。 在這種情況下,您應該檢查對象的存在,例如:
resp.json( res && res.rate || {} )
這里有另一個有關在這些情況下如何處理錯誤的示例:
app.param('user', function(req, res, next, id) {
// try to get the user details from the User model and attach it to the request object
User.find(id, function(err, user) {
if (err) {
next(err);
} else if (user) {
req.user = user;
next();
} else {
next(new Error('failed to load user'));
}
});
});
如果找不到請求的查詢,MongoDB將返回一個空對象。 因此,正如安東尼奧·瓦爾(Antonio Val)在他的回答中所假定的那樣,您需要考慮如何處理這些響應。
但是,對錯誤的處理與使用next()
可以不同,例如將resp
傳遞給用於處理錯誤的函數,該函數使用錯誤對象或其他自定義消息調用resp.json()
並添加statusCode,以便端點的被調用方還可以處理錯誤。
例如,更改在任何地方調用此命令:
if ( err ) {
console.error("1 mess " + err)
}
對此:
if ( err ) {
console.error("1 mess " + err)
handleErrors(resp, err)
}
然后創建功能handleErrors()
:
function handleErrors(resp, err) {
// its up to you how you might parse the types of errors and give them codes,
// you can do that inside the function
// or even pass a code to the function based on where it is called.
resp.statusCode = 503;
const error = new Error(err);
resp.send({error})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.