我有以下代码。有错误处理中间件,当我在浏览器上打开localhost:3000时会调用该中间件,但是响应永远不会是“系统暂时不可用”。相反,我收到错误消息“我的自定义错误”以及完整的堆栈跟踪。
我的理解是错误的,一旦出现未处理的错误,就会通过express调用错误中间件?/
CODE
let express = require('express');
let app = express();
let pug = require('pug');
let session = require('express-session');
let passport = require('passport');
require('dotenv').config();
app.listen(3000,"",()=>{
console.log('server started');
});
// set express properties. these properties can be had anywhere in the code
app.set('title','Sample application using Express, Expression session, Pug, Socktet and Passport');
// for pug
app.set('view engine','pug');
app.set('views','./pages');
console.log(process.env.ExpressSecret);
console.log(process.env.Port);
// use the express session to se the cookie,
// use function can take a series of middlewares
app.use( session({
secret: process.env.ExpressSecret,
saveUninitialized:true,
resave:true
}),passport.initialize(),passport.session())
app.use((err, req, res,next) => {
console.error(err.stack);
res.status(500).json({ error: 'system is unavailable for the moment' });
});
app.get('/',(request, response)=>{
throw new Error('my custom error');
});
答案 0 :(得分:1)
您需要在其他app.use()之后定义错误处理中间件并路由调用。
app.use( session({
secret: process.env.ExpressSecret,
saveUninitialized:true,
resave:true
}),passport.initialize(),passport.session())
app.get('/',(request, response)=>{
throw new Error('my custom error');
});
app.use((err, req, res,next) => {
console.error(err.stack);
res.status(500).json({ error: 'system is unavailable for the moment' });
});