2017-04-19 152 views
0

我是新來表達+ node.js,所以我寫了一個休息API使用貓鼬。數據庫錯誤等處理運行時錯誤的最佳方法是什麼?如何處理Express應用程序的運行時錯誤?

我已經在快遞文檔中看到,您可以使用中間件function(err, res, req, next)來處理此錯誤,並且您可以調用此函數僅調用next(err)。那好了,假設你有一個User moongose模型和一個控制器,你寫這個函數:

const find = (email, password) => { 
    User.find({ email: email }, (err, doc) => { 
    if (err) { 
     // handle error 
    } 
    return doc; 
    }); 
}; 

然後,你在另一個文件中有一條路徑的處理程序:

router.get('/users', (req, res) => { 
    userController.find(req.body.email); 
}); 

所以,在這一點,你可以處理在模型中寫入throw(err)的mongo錯誤,並在控制器中使用try/catch然後調用next(err)對不對?但我讀過在JavaScript中使用try/catch並不是一個好習慣,因爲它創建了一個新的執行上下文等。

在Express中處理這種錯誤的最佳方法是什麼?

+2

沒有什麼錯誤使用'嘗試/ catch'語句。就我個人而言,我會爲這種操作創建'Promises'的方法,以便我可以使用'.catch'進行錯誤處理。 –

回答

1

我會建議你使用承諾。它不僅使你的代碼更清晰,而且錯誤處理更容易。作爲參考,您可以訪問thisthis

如果你使用貓鼬,你可以插入你自己的諾言庫。

const mongoose = require('mongoose'); 
mongoose.connect(uri); 

// plug in the promise library: 
mongoose.Promise = global.Promise; 

mongoose.connection.on('error', (err) => { 
    console.error(`Mongoose connection error: ${err}`) 
    process.exit(1) 
}) 

而且使用它象下面這樣:

在控制器:

const find = (email) => { 
    var userQuery = User.find({ email: email }); 
    return userQuery.exec(); 
}; 

在路由器:

router.get('/users', (req, res) => { 
    userController.find(req.body.email).then(function(docs){ 
     // Send your response 
    }).then(null, function(err){ 
     //Handle Error 
    }); 
}); 
相關問題