gpt4 book ai didi

javascript - 如何处理 Node.js/express 中的错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:48 25 4
gpt4 key购买 nike

我试图捕获错误而不是抛出错误。我尝试尝试/捕获,但意识到这不起作用,所以我有点无所适从。这两个错误与 mongodb 相关,但是我认为 Node/express 错误仍然会抛出。

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,它的发生是因为当没有任何结果时,你从 MongoDB 得到 undefined,但这不是一个错误,所以它不会进入 if。在这些情况下您应该检查对象是否存在,例如:

resp.json( res && res.rate || {} )

Here您还有另一个关于如何处理这些情况下的错误的示例:

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'));
}
});
});

关于javascript - 如何处理 Node.js/express 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49326493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com