如果您使用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
以某種方式傳遞錯誤。
謝謝,你的有用的答案澄清了很多關於我的錯誤處理。 – Sonson123 2012-08-20 11:14:44
很好的答案!特別是關於使用next()直接綁定到ExpressJS的錯誤處理中間件的建議。 – 2012-10-22 18:35:14
這不適用於mongoose.connection.on('error',handler);或conn.on('error',handler);對我來說,我將handler定義爲console.log()第一個參數,但沒有任何內容出現在服務器控制檯上。 – Vadorequest 2014-01-12 16:22:51