mongoose / node如何处理异常

时间:2014-07-10 23:14:04

标签: node.js mongoose

我在保存模型时进行了验证。验证是针对空值并尝试拆分它并且错误输出..抛出节点本身。我正在通过一个回调来保存它没有被调用...但如果我有一个正确的错误(当我修剪并执行检查并发送错误它调用回调..)应如何正常处理。

C:\WN\models\user.coffee:18
                        # validator: wed.checkCity
                      ^
TypeError: Cannot call method 'split' of undefined
    at model.mongoose.Schema.aboutme.validate (C:\WN\models\user.coffee:18:23)
    at C:\WN\node_modules\mongoose\lib\schematype.js:627:28
    at Array.forEach (native)
    at SchemaString.SchemaType.doValidate (C:\WN\node_modules\mongoose\lib\schematype.js:614:19)
    at C:\WN\node_modules\mongoose\lib\document.js:956:9
    at process._tickCallback (node.js:415:13)

1 个答案:

答案 0 :(得分:0)

这里是我用来捕获Node.js抛出的异常的代码

// Error configuration
function bootErrorHandler(app) {

  // When no more middleware require execution, aka
  // our router is finished and did not respond, we
  // can assume that it is "not found". Instead of
  // letting Connect deal with this, we define our
  // custom middleware here to simply pass a NotFound
  // exception

  app.use(function(req, res, next){
    next(new NotFound(req.url));
  })

  // Provide our app with the notion of NotFound exceptions

  function NotFound(path){
    this.name = 'NotFound'
    if (path) {
      Error.call(this, 'Cannot find ' + path)
      this.path = path
    } else {
      Error.call(this, 'Not Found')
    }
    Error.captureStackTrace(this, arguments.callee)
  }

  /**
   * Inherit from `Error.prototype`.
   */

  NotFound.prototype.__proto__ = Error.prototype;

  // We can call app.error() several times as shown below.
  // Here we check for an instanceof NotFound and show the
  // 404 page, or we pass on to the next error handler.

  // These handlers could potentially be defined within
  // configure() blocks to provide introspection when
  // in the development environment.

  //var logFile = fs.createWriteStream(__dirname + '/log/error', {'flags': 'a'});

  var mongooseError = function(err, res){
      var messages = {
        'required': "%s is required",
        'min': "%s below minimum",
        'max': "%s above maximum",
        'enum': "%s not an allowed value"
      };
      var errors = [];
      _.each(Object.keys(err.errors), function(field){
        var errObj = err.errors[field];
        if (!messages.hasOwnProperty(errObj.type))
            errors.push(errObj.type);
        else{
            errors.push(require('util').format(messages[errObj.type], errObj.path));
        }
      });
        res.render('info/500', {
            status: 500,
            error: errors,
            showStack: '',
            title: 'Oops! Something went wrong',
            layout: 'layouts/500'
        });
  }

  app.error(function(err, req, res, next){
          //logFile.write('\r\n===' + new Date() + '===\r\n');
          //logFile.write(err.stack);

          if (err instanceof NotFound) {
                  logger.error(err.stack);
                  res.render('info/404', {
                          status: 404,
                          error: err,
                          showStack: app.settings.showStackError,
                          title: 'Oops! The page you requested desn\'t exist'
                  })
          }
          else {
                  logger.error(err.stack);
                  if (err.name === 'ValidationError')
                     mongooseError(err, res);
                  else
                    res.render('info/500', {
                        status: 500,
                        error: err,
                        showStack: app.settings.showStackError,
                        title: 'Oops! Something went wrong!',
                        layout: 'layouts/500'
                    });
         }
  })

}

您还可以在节点应用文件的开头添加以下代码。

process.on('uncaughtException', function (err) {
  if ('stack' in err) {
    console.log(err.stack);
  }
});