2016-10-13 6 views
0

this tutorialの認証コードを私のアプリケーションに組み込みました。すべてが機能しています。今度は、データベースのエラー処理をより堅牢にするために戻っていきます。下のコード(チュートリアルから)でsave()のつまずきが発生した場合、なぜ彼らはthrowエラーになりますか?より優雅に扱わない理由はありますか?おそらくのようなもの:チュートリアルからPassportとMongooseを使用したデータベースエラー処理

if (err) 
    return done(err, false, req.flash('signupMessage', 'Encountered database error.')); 

passport.use('local-signup', new LocalStrategy({ 
    // by default, local strategy uses username and password, we will override with email 
    usernameField : 'email', 
    passwordField : 'password', 
    passReqToCallback : true // allows us to pass back the entire request to the callback 
}, 
function(req, email, password, done) { 
    // asynchronous 
    // User.findOne wont fire unless data is sent back 
    process.nextTick(function() { 
    // find a user whose email is the same as the forms email 
    // we are checking to see if the user trying to login already exists 
    User.findOne({ 'local.email' : email }, function(err, user) { 
     // if there are any errors, return the error 
     if (err) 
      return done(err); 
     // check to see if theres already a user with that email 
     if (user) { 
      return done(null, false, req.flash('signupMessage', 'That email is already taken.')); 
     } else { 
      // if there is no user with that email 
      // create the user 
      var newUser   = new User(); 
      // set the user's local credentials 
      newUser.local.email = email; 
      newUser.local.password = newUser.generateHash(password); 
      // save the user 
      newUser.save(function(err) { 
       if (err) 
        throw err; 
       return done(null, newUser); 
      }); 
     } 
    });  
    }); 
})); 

答えて

1

解決策は単純です:

newUser.save(function(err) { 
    if (err) { 
    return done(err); 
    } 
    return done(null, newUser); 
}); 

でもマングースにdocumentation省は、例外をスローせずに行われます。

あなたが読んでいる解決策は古すぎます:2012年12月4日。純粋なソースから最新のドキュメントを読んでみませんか?

この読み:http://passportjs.org/docs/configure



BONUSを:私がプラグインmongoosefindOrCreate

+0

はいを​​使って、あなたのコードを短縮することをお勧めします。それは私が考えていることです(私はそれをキャッチし、ユーザーにエラーメッセージを表示できるようにフラッシュメッセージを追加しました)。 – tcquinn

+0

もう一度ありがとうございます。ボーナスの質問: 'process.nextTick()'はどうなっていますか?私は文字通りその関数が何をしているのか理解していると思いますが、なぜ 'findOne()'を呼び出しスタックにプッシュする必要がありますか?すでにコールバック関数の中にラップされています。 – tcquinn

+0

あなたのコードでnextTickは効果がありません。次のティックのアイデアは、次のステートメントが完了した後でラップされたスコープを呼び出すことです。したがって、あなたのコードには次の声明はありません。この文書を読む:この文書のhttps://howtonode.org/understanding-process-next-tickあなたはそれが何をするかを説明するfoo-barの例を見るでしょう。 – num8er

関連する問題