Reputation: 3216
This is a cool little middleware that returns a 405 error if the req.url matches one of the other routes connected to the same router object.
If it finds a match it will check to see if there is a matching http verb if there is no matching http verb it will set the flag to true and trigger the error.
My problem is that when next(err)
gets called the next tick does not get processed. The server just blows up with an error as if i actually threw one.
I want the next tick to be processed (which is my error handeling middleware).
start.js
var express = require('express'),
router = express.Router();
//Other routes
router.use( function(req, res, next) {
var flag = false;
for (var i = 0, rl = router.stack.length; i < rl; i++) {
var route = router.stack[i].route;
if (route && req.url.toLowerCase() === route.path.toLowerCase()) {
for (var method in route.methods) {
if (route.methods.hasOwnProperty(method)) {
if(method.toLowerCase() !== req.method.toLowerCase()){
flag = true;
}
}
}
}
};
if (flag) {
var err = new Error('Method Not Allowed');
err.status = 405;
return next(err);
}
return next();
});
module.exports = router
routes.js
var express = require('express'),
router = express.Router();
router.use(require('../middlewares/successHandler_logger'));
router.use('/start', require('./start/start'));
router.use('/login', require('./login/login'));
router.use(require('../middlewares/errorHandeling'));
module.exports = router
errorHandler.js
var express = require('express'),
router = express.Router();
router.use(function(err, req, res, next) {
err.status = err.status || 500;
if (!err.json) {
err.json = {
status:err.status,
success: false,
message: 'oops',
}
};
res.status(err.status).json(err.json);
console.log(err.stack);
});
module.exports = router
Upvotes: 1
Views: 694
Reputation: 707188
I think the issue is that you have multiple routers and the error handling chaining you want does not work across routers.
I'd suggest you only create one router and share it. For example, in errorHandler.js
, you can do this:
module.exports = function(err, req, res, next) {
err.status = err.status || 500;
if (!err.json) {
err.json = {
status:err.status,
success: false,
message: 'oops',
}
};
res.status(err.status).json(err.json);
console.log(err.stack);
});
And, then this will still work:
router.use(require('../middlewares/errorHandeling'));
You would then similarly have to use one common router in the other places.
Upvotes: 1