2017-04-19 151 views
0

我是新来表达+ node.js,所以我写了一个休息API使用猫鼬。数据库错误等处理运行时错误的最佳方法是什么?如何处理Express应用程序的运行时错误?

我已经在快递文档中看到,您可以使用中间件function(err, res, req, next)来处理此错误,并且您可以调用此函数仅调用next(err)。那好了,假设你有一个User moongose模型和一个控制器,你写这个函数:

const find = (email, password) => { 
    User.find({ email: email }, (err, doc) => { 
    if (err) { 
     // handle error 
    } 
    return doc; 
    }); 
}; 

然后,你在另一个文件中有一条路径的处理程序:

router.get('/users', (req, res) => { 
    userController.find(req.body.email); 
}); 

所以,在这一点,你可以处理在模型中写入throw(err)的mongo错误,并在控制器中使用try/catch然后调用next(err)对不对?但我读过在JavaScript中使用try/catch并不是一个好习惯,因为它创建了一个新的执行上下文等。

在Express中处理这种错误的最佳方法是什么?

+2

没有什么错误使用'尝试/ catch'语句。就我个人而言,我会为这种操作创建'Promises'的方法,以便我可以使用'.catch'进行错误处理。 –

回答

1

我会建议你使用承诺。它不仅使你的代码更清晰,而且错误处理更容易。作为参考,您可以访问thisthis

如果你使用猫鼬,你可以插入你自己的诺言库。

const mongoose = require('mongoose'); 
mongoose.connect(uri); 

// plug in the promise library: 
mongoose.Promise = global.Promise; 

mongoose.connection.on('error', (err) => { 
    console.error(`Mongoose connection error: ${err}`) 
    process.exit(1) 
}) 

而且使用它象下面这样:

在控制器:

const find = (email) => { 
    var userQuery = User.find({ email: email }); 
    return userQuery.exec(); 
}; 

在路由器:

router.get('/users', (req, res) => { 
    userController.find(req.body.email).then(function(docs){ 
     // Send your response 
    }).then(null, function(err){ 
     //Handle Error 
    }); 
}); 
相关问题