Reputation: 49
I have the following code. There is the error handling middleware, which does get called when i open localhost:3000 on browser, but the response is never 'system is unavailable for the moment'. Instead i get the error message "my custom error" along with the full stack trace.
Is my understanding incorrect that error middleware is called by express once there is an unhandeled error ?/
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');
});
Upvotes: 0
Views: 602
Reputation: 159
You need to define error-handling middleware last, after other app.use() and routes calls.
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' });
});
https://expressjs.com/en/guide/error-handling.html
Upvotes: 2