在一个地方进行猫鼬错误处理

时间:2012-08-22 04:45:15

标签: node.js error-handling coffeescript mongoose

我在mongoose docs中发现我可以处理我想要的错误。所以你可以这样做:

Product.on('error', handleError);

但是这个handleError方法的签名是什么?我想要这样的东西:

handleError = (err) ->
  if err
    console.log err
    throw err

但这不起作用。

2 个答案:

答案 0 :(得分:5)

节点中error事件的标准是提供一个参数,这是错误本身。根据我的经验,即使提供附加参数的少数库总是将错误留在第一个,因此您可以使用带有签名function(err)的函数。

您还可以在GitHub上查看来源;这里是发布error事件的预保存挂钩,当出现错误时,错误作为参数:https://github.com/LearnBoost/mongoose/blob/cd8e0ab/lib/document.js#L1140

在JavaScript中还有一种非常简单的方法可以查看传递给函数的所有参数:

f = ->
  console.log(arguments)

f()                     # {}
f(1, "two", {num: 3})   # { '0': 1, '1': 'two', '2': { num: 3 } }
f([1, "two", {num: 3}]) # { '0': [ 1, 'two', { num: 3 } ] }

现在到你的功能不起作用的部分;你的代码究竟是如何读取的?名称handleError在任何方面都不特别;你需要这两个中的一个:

选项1 :定义函数,并将引用传递给事件注册:

handleError = (err) ->
  console.log "Got an error", err

Product.on('error', handleError)

选项2 :定义内联函数:

Product.on 'error', (err) ->
  console.log "Got an error", err

答案 1 :(得分:0)

花了1个小时来找到简单,常见的地点和最佳方法:

下面的代码在express.js中:

app.js中:

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {

  // set locals, only providing error in development
  if (req.app.get('env') === 'development') {
    res.locals.message = err.message;
    res.locals.error = err;
    console.error(err);
  } else {
    res.locals.message = 'Something went wrong. Please try again!';
    res.locals.error = {};
  }

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

product-controller.js中:

let handleSuccess = (req, res, next, msg) => {
  res.send(msg + ' success ');
};

let handleError = (req, res, next, msg, err) => {
  // Create an error and pass it to the next function
  next(new Error(msg + ' error ' + (err.message || '')));
};

我们还可以将上述通用代码放在一个通用文件中,然后导入该文件,以在其他控制器或任何其他文件中重用以上功能。

相关问题