Reputation: 137
According to Express 5 documentation, route handlers and middleware that return a Promise will call next(value) automatically when they reject or throw an error. I've been trying to use this for the past few hours, but I don't know what I'm doing wrong. Whatever I do, my error handler doesn't get called.
Here's what I'm doing:
//app.js
import express from 'express';
import defaultRouter from './routes/index.js';
//app.use express.json
//app.use express.urlencoded
//app.use session
//app.use flash
//etc.
app.use('/', defaultRouter);
app.use(express.static(`${dirname}/assets/`));
app.use(async (err, req, res, next) => {
console.log('Error happened!'); //This actually doesn't happen. Why?
console.log(err);
});
//app.listen
In the route file, I'm assigning the "/" path to the homeController's index function as follows:
// ./routes/index.js
import express from 'express';
import * as homeController from '../controllers/home.js';
const router = express.Router({ mergeParams: true });
router.route('/').get(homeController.index);
export default router;
Finally, here's the home controller where I throw an exception:
// ../controllers/home.js
export const index = async (req, res) => {
throw new Error('mine');
};
This is where the Express 5 is supposed to pass the error to the "next" automatically. However, since this is not done for some reason, the "async (err, req, res, next)" handler defined in the app.js is not hit. What am I doing wrong and how to fix this?
Upvotes: 0
Views: 89