2017-08-20 8 views
2

express用に生成されたテンプレートに従います。 app.jsでは私の理解パー次のスニペットExpressミドルウェア・エラー・ハンドラー

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'); 
}); 

があり、ミドルウェアは、ハンドラをエラーに404件のハンドラへapp.use('/users', users)から順に実行されます。私の質問は、どのようにエラーハンドラに到達し、この行を実行することが可能になりますres.status(err.status || 500);?失敗したリクエストはすべて404ハンドラに渡されてからステータスコードが404になることはありませんか?もし私が何かを見逃しているなら教えてください!ありがとうございます

答えて

3

いいえ、そうではありません。

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.

ルートが見つからなかった場合、最後に宣言ミドルウェアが呼んでいる:あなたはこれらのイベントハンドラ宣言を見れば、あなたは追加のerrのパラメータがあり、未処理のエラーのためにそのエラーハンドラが表示されます、それは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'); 
}); 
前に処理する必要があります参照してください。
関連する問題