2015-06-26 11 views
2

是否可以使用Express 4向前端發送JSON響應,以指示出現錯誤,並調用Express中間件內的下一個(err)這樣錯誤可以由服務器來處理?還是這些電話完全相互排斥?JSON響應並調用Express中的next()

我現在的假設是,你可以這樣做:

app.get('/', function(req, res, next) { 
    res.json({ error : true }); 
}); 

,你可以這樣做:

app.get('/', function(req, res, next) { 
    next(new Error('here goes the error message'); 
}); 

,但你不能做到這一點

app.get('/', function(req, res, next) { 
    res.json({ error : true }); 
    next(new Error('here goes the error message'); 
}); 

和你不能這樣做:

app.get('/', function(req, res, next) { 
    next(new Error('here goes the error message'); 
    res.json({ error : true }); 
}); 
+0

您能否包含一些示例代碼? – kdbanman

+0

@kdbanman喜歡什麼?它看起來像發送json然後調用'next'。 –

+0

你是什麼意思「這樣錯誤可以由服務器來處理」? – IvanJ

回答

5

它們不是相互排斥的。例如(而不是中間件我使用的路由處理程序來證明,但原理上是相同的):

app.get('/', function(req, res, next) { 
    res.json({ error : true }); 
    next(new Error('something happened')); 
}); 

app.get('/another', function(req, res, next) { 
    next(new Error('something happened')); 
}); 

app.use(function(err, req, res, next) { 
    console.error(err); 
    if (! res.headersSent) { 
    res.send(500); 
    } 
}); 

你可以檢查在錯誤處理程序res.headersSent確保發送響應(如果不是,錯誤處理程序應該自己發送一個)。

+0

酷,讓我給那是我認爲他們獨享的時間最長的一次 – Olegzandr