2017-08-20 29 views
2

在生成的快遞模板之後。在app.js還有下面的代碼片段快遞中間件錯誤處理程序

app.use('/users', users); 

// catch 404 and forward to error handler 
app.use(function(req, res, next) { 
    var err = new Error('Not Found'); 
    err.status = 404; 
    next(err); 
}); 

// error handler 
app.use(function(err, req, res, next) { 
    // set locals, only providing error in development 
    res.locals.message = err.message; 
    res.locals.error = req.app.get('env') === 'development' ? err : {}; 

    // render the error page 
    res.status(err.status || 500); 
    res.render('error'); 
}); 

按我的理解,中間件會爲了逃避app.use('/users', users)到404處理器到錯誤處理程序。我的問題是如何才能達到錯誤處理程序並執行此行res.status(err.status || 500);?不是每個失敗的請求都首先通過404處理程序,因此得到的狀態碼是404?請讓我知道如果我失去了一些東西!謝謝

回答

3

不,它不會。如果你看一下這些事件處理程序的聲明,你會看到未處理的錯誤的錯誤處理程序中,有一個額外的err參數:

app.use(function(req, res, next) { 
app.use(function(err, req, res, next) { 

Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the next object, you must specify it to maintain the signature. Otherwise, the next object will be interpreted as regular middleware and will fail to handle errors. For details about error-handling middleware.

所以,當沒有找到路徑,最後宣佈中間件調用,它是404錯誤處理程序。

但是,如果您致電next,並顯示錯誤:next(err)或者您的代碼引發錯誤,則表明最後一個錯誤處理程序正在調用。

1

Wont every failed request be passed through 404 handler first and therefor getting the status code of 404?

號,404路線僅僅是一個標準的中間件通常有線了最後,這意味着如果沒有其他途徑處理,他們最終將打擊404

500請求是一種特殊類型的中間件,你會注意到它有4個參數(第一個是錯誤參數)。只要您致電next並出現錯誤或此類問題的任何種類的數據,就會調用此中間件。

the docs

1

系統誤差應404

app.use('/users', users); 

// error handler 
app.use(function(err, req, res, next) { 
    // No routes handled the request and no system error, that means 404 issue. 
    // Forward to next middleware to handle it. 
    if (!err) return next(); 

    // set locals, only providing error in development 
    res.locals.message = err.message; 
    res.locals.error = req.app.get('env') === 'development' ? err : {}; 

    // render the error page 
    res.status(err.status || 500); 
    res.render('error'); 
}); 

// catch 404. 404 should be consider as a default behavior, not a system error. 
app.use(function(req, res, next) { 
    res.status(404); 
    res.render('Not Found'); 
}); 
前處理