我是一个绝对的NodeJS初学者,想要用Express和Mongoose创建一个简单的REST-Web服务。
在一个中心位置处理Mongoose错误的最佳做法是什么?
当发生数据库错误的任何地方时,我想返回一个带有错误消息的Http-500-Error-Page:
if(error) {
res.writeHead(500, {'Content-Type': 'application/json'});
res.write('{error: "' + error + '"}');
res.end();
}
在旧教程http://blog-next-stage.learnboost.com/mongoose/中,我读到了一个全局错误监听器:
Mongoose.addListener('error',function(errObj,scope_of_error));
但这似乎不起作用,我无法在official Mongoose documentation中找到有关此侦听器的内容。我是否在每次发出Mongo请求后检查错误?
答案 0 :(得分:43)
如果您使用的是Express,通常会直接在您的路线中或在mongoose上构建的api中处理错误,并将错误转发到next
。
app.get('/tickets', function (req, res, next) {
PlaneTickets.find({}, function (err, tickets) {
if (err) return next(err);
// or if no tickets are found maybe
if (0 === tickets.length) return next(new NotFoundError));
...
})
})
可以在error handler middleware中嗅探NotFoundError
以提供自定义消息。
有些抽象是可能的,但您仍然需要访问next
方法才能将错误传递到路径链中。
PlaneTickets.search(term, next, function (tickets) {
// i don't like this b/c it hides whats going on and changes the (err, result) callback convention of node
})
至于集中处理猫鼬错误,并不是真正处理所有错误的地方。可以在几个不同的级别处理错误:
您的模型使用的connection
会发出 connection
个错误,所以
mongoose.connect(..);
mongoose.connection.on('error', handler);
// or if using separate connections
var conn = mongoose.createConnection(..);
conn.on('error', handler);
对于典型的查询/更新/删除,错误将传递给您的回调。
PlaneTickets.find({..}, function (err, tickets) {
if (err) ...
如果您没有传递回调,那么如果您正在侦听它,则会在模型上发出错误:
PlaneTickets.on('error', handler); // note the loss of access to the `next` method from the request!
ticket.save(); // no callback passed
如果您没有通过回调并且没有在model
级别收听错误,则会在模型connection
上发出错误。
这里的关键要点是,您希望以某种方式访问next
以传递错误。