查看快遞error-pages示例。原則是首先註冊您的應用程序路線,然後爲所有其他未映射到路線的請求註冊一個捕獲所有404處理程序。最後,註冊500處理程序,如下所示:
// "app.router" positions our routes
// specifically above the middleware
// assigned below
app.use(app.router);
// Since this is the last non-error-handling
// middleware use()d, we assume 404, as nothing else
// responded.
app.use(function(req, res, next){
// the status option, or res.statusCode = 404
// are equivalent, however with the option we
// get the "status" local available as well
res.render('404', { status: 404, url: req.url });
});
// error-handling middleware, take the same form
// as regular middleware, however they require an
// arity of 4, aka the signature (err, req, res, next).
// when connect has an error, it will invoke ONLY error-handling
// middleware.
// If we were to next() here any remaining non-error-handling
// middleware would then be executed, or if we next(err) to
// continue passing the error, only error-handling middleware
// would remain being executed, however here
// we simply respond with an error page.
app.use(function(err, req, res, next){
// we may use properties of the error object
// here and next(err) appropriately, or if
// we possibly recovered from the error, simply next().
res.render('500', {
status: err.status || 500
, error: err
});
});
是的,我覺得我已經通過了Express例子。但無論如何,這非常有幫助。我在視圖中創建了自己的500.ejs等等,現在可以根據需要進行渲染,但是在指定時也可以添加自己的錯誤消息。謝謝。 – tuddy
當我使用404處理添加app.use()時,出於某種原因,它會將我的所有路由混入公共文件夾中。像/stylesheets/style.css一下子就會丟失,因爲它通常是從我的ejs模板訪問的。對此有何建議? – netpoetica
我能夠解決這個問題,快速app.use()中間件打破我的靜態路徑通過簡單地移動app.use(靜態....)在這裏給出的例子 – netpoetica