i am making a nodejs web api and i have a function that returns a user object that is associated with a given authentication token:
module.exports.getByToken = function (token_value, callback)
{
mongoose.model('tokens').findOne({ value: token_value }).exec(function (err, token)
{
if (err || token == null)
{
var error = new Error('couldn\'t find user of the given token');
callback(error, null);
}
else
{
mongoose.model('users').find({ _id: token.user }).exec(callback);
}
});
};
As you can see, i am passing the error back to the callback instead of throwing it. Am i doing it right?
This function is called from an authentication middleware:
app.use('/api', function (req, res, next)
{
var token = req.headers.authorization;
users.getByToken(token, function (err, user)
{
if (err || user == null)
{
res.status(401).end('Unauthorized');
}
else
{
app.locals.user = user;
next();
}
});
});
So the idea of passing the error back to the callback works conveniently. But is this the right way to handle errors?
Can it block the main thread? Should i throw the error instead and explicitly catch it in the middleware?
Thanks, Arik