2014-07-10 5 views
0

모델 저장 중에 유효성을 검사했습니다. 유효성 검사는 빈 값에 대해 진행하고 그것을 분할하려고 시도하고 오류가 발생하면 노드 자체에 던져집니다. 호출하지 않고 저장하기 위해 콜을 전달하고 있습니다 ...하지만 적절한 에러가 발생하면 (체크하고 콜백 호출을 false로 보내면) 어떻게 정상적으로 처리되어야합니다. 여기mongoose/node 예외 처리 방법

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) 
+0

실제로 오류가 발생하는 코드를 붙여 넣으시겠습니까? – cvng

+0

문제가되지 않습니다. 오류를 해결하기 위해 찾고 있지 않습니다. 내가 언급했듯이 .. 예외가 있는지 확인하려고 노력 중입니다. 노드 서버를 다운 시켜서는 안됩니다. 콜백은 save 메소드에 콜백하고 싶었습니다 ... 콜백은 유효성 검사에서 false로 테스트했기 때문에 콜백이 제대로 작동했습니다. 언급 한대로 다시 돌아옵니다. – coool

+0

일반적으로 유효성 검사기에 검사를 포함하면 그렇지 않은 코드를 막을 수 있습니다. 예외가 throw되지 않게합니다. – JohnnyHK

답변

0

나는 또한 당신이 당신의 노드 응용 프로그램 파일의 시작 부분에 다음 코드를 추가 할 수 있습니다

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

} 

Node.js를

에 의해 던져진 예외를 잡기 위해 사용하는 어떤 코드.

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