Search code examples
javascriptnode.jsmiddleware

Node js error handler issue


The general topic of this ticket is node js middleware and error handlers

When a user accesses a link like site.com/user/username, I want to print a message if a user with the specified username exists.

I have written 2 middleware functions to implement that: the first one is users and the 2nd one is errorHandler.

But for some reason the whole program doesn't work. Please tell me where I went wrong. Here's the code:

let connect = require('connect');
let port = 3000;

let api = connect()
	.use(users)
	.use(errorHandler)
	.listen(port);

var db = {
	users: [
		{ name: 'tobi' },
		{ name: 'loki' },
		{ name: 'jane' }
	]
};

function users(req, res, next) {
	var match = req.url.match(/^\/user\/(.+)/)
	if (match) {
		var user = db.users[match[1]];
		if (user) {
			res.setHeader('Content-Type', 'application/json');
			res.end(JSON.stringify(user));
		} else {
			var err = new Error('User not found');
			err.notFound = true;
			next(err);
		}
	} else {
		next();
	}
}


function errorHandler(err, req, res, next) {
	console.error(err.stack);
	res.setHeader('Content-Type', 'application/json');
	if (err.notFound) {
		res.statusCode = 404;
		res.end(JSON.stringify({ error: err.message }));
	} else {
		res.statusCode = 500;
		res.end(JSON.stringify({ error: 'Internal Server Error' }));
	}
}


Solution

  • I think the issue is looking for a solution in the wrong part of your db object. your code as written is looking for db.users['toby'] when it should be looking for db.users[0].name = 'toby' I would recommend using the array.prototype.find method to search your array of names

    function users(req, res, next) {
      let match = req.url.match(/^\/user\/(.+)/)
    
      if (!match) { next() }
    
      let user = db.users.find(v => v.name === match);
    
      if (user === undefined) {
        let err = new Error('User not found')
        err.notFound = true;
        next(err);
      }
    
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify(user));
    }