2012-08-08 93 views
22

我是絕對的NodeJS初學者,想用Express和Mongoose創建一個簡單的REST-Webservice。用Mongoose處理錯誤

在一箇中心位置處理貓鼬錯誤的最佳做法是什麼?

在任何地方發生的數據庫錯誤我想用一個錯誤信息返回一個Http-500-錯誤頁:

if(error) { 
    res.writeHead(500, {'Content-Type': 'application/json'}); 
    res.write('{error: "' + error + '"}'); 
    res.end(); 
} 

在舊的輔導http://blog-next-stage.learnboost.com/mongoose/我讀到一個全局錯誤監聽器:

Mongoose.addListener('error',function(errObj,scope_of_error)); 

但是這似乎不起作用,我無法找到有關此聽衆的official Mongoose documentation中的內容。我是否在每次Mongo請求後檢查錯誤?

回答

40

如果您使用Express,通常會直接在路由中或在貓鼬頂部構建的API內處理錯誤,並將錯誤轉發至next

app.get('/tickets', function (req, res, next) { 
    PlaneTickets.find({}, function (err, tickets) { 
    if (err) return next(err); 
    // or if no tickets are found maybe 
    if (0 === tickets.length) return next(new NotFoundError)); 
    ... 
    }) 
}) 

NotFoundError可以在你的error handler middleware嗅探提供定製的消息。

一些抽象是可能的,但您仍需要訪問next方法才能將錯誤傳遞給路徑鏈。

PlaneTickets.search(term, next, function (tickets) { 
    // i don't like this b/c it hides whats going on and changes the (err, result) callback convention of node 
}) 

至於集中處理貓鼬錯誤,那裏不是真的一個地方處理所有的問題。錯誤可以在幾個不同的層次進行處理:正在使用,所以

mongoose.connect(..); 
mongoose.connection.on('error', handler); 

// or if using separate connections 
var conn = mongoose.createConnection(..); 
conn.on('error', handler); 

對於典型的查詢/更新

connection錯誤發出的connection您的模型/刪除錯誤傳遞給你的回調。

PlaneTickets.find({..}, function (err, tickets) { 
    if (err) ... 

如果不通過對模型發出錯誤的回調,如果你正在聽吧:

PlaneTickets.on('error', handler); // note the loss of access to the `next` method from the request! 
ticket.save(); // no callback passed 

如果不傳遞迴調,而不是聽他們將在connection的模型上發出model級別的錯誤。

這裏關鍵的一點是,您希望訪問next以某種方式傳遞錯誤。

+0

謝謝,你的有用的答案澄清了很多關於我的錯誤處理。 – Sonson123 2012-08-20 11:14:44

+0

很好的答案!特別是關於使用next()直接綁定到ExpressJS的錯誤處理中間件的建議。 – 2012-10-22 18:35:14

+0

這不適用於mongoose.connection.on('error',handler);或conn.on('error',handler);對我來說,我將handler定義爲console.log()第一個參數,但沒有任何內容出現在服務器控制檯上。 – Vadorequest 2014-01-12 16:22:51