【问题标题】:Mongoose error handling in one placeMongoose 错误处理集中在一处
【发布时间】:2012-08-17 11:33:00
【问题描述】:

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

Product.on('error', handleError);

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

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

但这不起作用。

【问题讨论】:

    标签: node.js error-handling coffeescript mongoose


    【解决方案1】:

    在 Node 中,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
    

    【讨论】:

    • 我这样做了,但发生错误时我在控制台中看不到我的消息。
    • 值得注意的是,如果您定义回调,处理程序将不会运行,因此如果您Product.save(function(err, doc) {}),则预计您将自己处理错误。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-12-28
      • 2012-08-05
      • 2014-01-07
      • 2013-09-04
      • 2017-01-11
      • 2020-10-24
      • 1970-01-01
      • 2013-02-07
      • 2013-11-30
      相关资源
      最近更新 更多