A great way to enhance your express middleware is by utilizing the error handling feature. By incorporating a middleware sequence, you have the flexibility to efficiently manage errors. Here's an example of how you can configure your express setup:
app.use(logger.connectLogger());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(routes);
app.use(errorConnect);
http.createServer(app).listen(config.port, function () {
logger.getLogger().info('My backend listening on port: ' + config.port);
});
Within my routes module, each route is mapped to its respective callback function:
// Methods exposed for backend API.
router.get('/status', ips.getStatus);
router.route('/ip')
.post(ips.keepIps)
.get(ips.getIps)
// NOT ALLOWED
.put(returnNotAllowed)
.delete(returnNotAllowed);
// Methods exposed and used by IP's frontend.
router.route('/front/ip')
.get(front.getIpsByFront)
.post(front.keepIpsByFront);
router.post('/login', login.login);
....
For instance, within one of these callback functions like the login
function below, I handle incoming requests in a structured manner:
/**
* Login user from frontend.
*/
exports.login = function(req, res, next) {
var username = req.body.username + '@System',
password = req.body.password,
server = req.body.server,
auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
loginApi.login(auth, server)
.then(function(result) {
res.statusCode = 200;
res.send(result);
})
.catch(function(error) {
next({
statusCode: 403,
message: 'Error in login'
});
});
};
If an error occurs, I simply invoke next
with a custom error object. Additionally, as showcased in the initial configuration setup, I have integrated an error management system using errorConnect
. This approach proves to be advantageous in deciphering any uncertainties regarding the usage of next()
.