Mongoose处理错误 [英] Error handling with Mongoose

查看:378
本文介绍了Mongoose处理错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个绝对的NodeJS初学者,希望用Express和Mongoose创建一个简单的REST-Webservice。



在一个中心处理Mongoose错误的最佳做法是什么?地点?



当发生数据库错误时,我想返回一个带有错误消息的Http-500错误页面:


$ b如果(错误){
res.writeHead(500,{'Content-Type':'application / json'}); $ b

  
res.write('{error:''+ error +'}');
res.end();
}

在旧教程http://blog-next-stage.learnboost.com/mongoose/ 我读到了一个全局错误监听器:


$ b $ Mongoose.addListener('error',function(errObj,scope_of_error)); b

  

但这似乎不起作用,我找不到关于此监听器的官方Mongoose文档。每次Mongo请求后,我是否检查错误?

解决方案

如果您使用Express,错误通常直接在您的路线或在一个建立在猫鼬之上的api内,将错误转发到下一个

 code> app.get('/ tickets',function(req,res,next){
PlaneTickets.find({},function(err,tickets){
if(err)return next(err);
//或者如果没有找到可能的票可能
if(0 === tickets.length)return next(new NotFoundError));
...
})
})

NotFoundError 可以在您的错误处理程序中间件中被嗅探,以提供自定义的信息。



有些抽象是可能的,但是您仍然需要访问下一个方法,以便将错误传递到路由链。

  PlaneTi ckets.search(term,next,function(ticket){
//我不喜欢这个b / c它隐藏了什么,改变了节点
的(err,result)回调约定)

对于集中处理mongoose错误,theres不是一个地方处理em全部。错误可以在几个不同的级别处理:



连接错误在连接您的模型正在使用,所以

  mongoose.connect(..); 
mongoose.connection.on('error',handler);

//或如果使用单独的连接
var conn = mongoose.createConnection(..);
conn.on('error',handler);

对于典型的查询/更新/删除错误传递给您的回调。

  PlaneTickets.find({..},function(err,tickets){
if(err)...

如果您不传递回调,则如果您正在监听,则会在模型上发出错误: / em>

  PlaneTickets.on('error',handler); //注意访问next方法从请求!
ticket.save(); //没有回调通过

如果您不会传回回调,并且不会在模型级别收听错误,他们将在模型连接 。



这里的关键摘要是您希望访问 next 以某种方式传递错误。 / p>

I am an absolute NodeJS beginner and want to create a simple REST-Webservice with Express and Mongoose.

Whats the best practice to handle errors of Mongoose in one central place?

When anywhere an database error occurs I want to return a Http-500-Error-Page with an error message:

if(error) {
  res.writeHead(500, {'Content-Type': 'application/json'});
  res.write('{error: "' + error + '"}');
  res.end();
}

In the old tutorial http://blog-next-stage.learnboost.com/mongoose/ I read about an global error listener:

Mongoose.addListener('error',function(errObj,scope_of_error));

But this doesn't seem to work and I cannot find something in the official Mongoose documentation about this listener. Have I check for errors after every Mongo request?

解决方案

If you're using Express, errors are typically handled either directly in your route or within an api built on top of mongoose, forwarding the error along to 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));
    ...
  })
})

The NotFoundError could be sniffed in your error handler middleware to provide customized messaging.

Some abstraction is possible but you'll still require access to the next method in order to pass the error down the route chain.

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

As for centrally handling mongoose errors, theres not really one place to handle em all. Errors can be handled at several different levels:

connection errors are emitted on the connection your models are using, so

mongoose.connect(..);
mongoose.connection.on('error', handler);

// or if using separate connections
var conn = mongoose.createConnection(..);
conn.on('error', handler);

For typical queries/updates/removes the error is passed to your callback.

PlaneTickets.find({..}, function (err, tickets) {
  if (err) ...

If you don't pass a callback the error is emitted on the Model if you are listening for it:

PlaneTickets.on('error', handler); // note the loss of access to the `next` method from the request!
ticket.save(); // no callback passed

If you do not pass a callback and are not listening to errors at the model level they will be emitted on the models connection.

The key take-away here is that you want access to next somehow to pass the error along.

这篇关于Mongoose处理错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆