我正在创建一个nodejs web api,我有一个函数返回一个与给定身份验证令牌相关联的用户对象:
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);
}
});
};
正如您所看到的,我将错误传递回回调而不是抛出它。我做得对吗?
从身份验证中间件调用此函数:
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();
}
});
});
因此将错误传递回回调的想法很方便。 但这是处理错误的正确方法吗?
可以阻止主线程吗? 我应该抛出错误而在中间件中明确地捕获它吗?
谢谢, 阿里克
答案 0 :(得分:2)
IMO你正在以正确的方式做到这一点。如果回调者不负责处理它,则应该返回错误作为第一个参数。如果您想要改进处理任何可能的错误的方法,您可以将中间件更改为:
app.use('/api', function (req, res, next){
var token = req.headers.authorization;
users.getByToken(token, function (err, user){
if (err){
res.status(500).end('Something went wrong :('); //token could be valid but you have lost your connection to DB or any other error
}else if (user == null){
res.status(401).end('Unauthorized');
}
else {
app.locals.user = user;
next();
}
});
});
答案 1 :(得分:0)
看起来是对的。它没有错。我会简化代码,或者用以下方式将中间件与路由分开:
app.use('/api',
auth.checkToken,
auth.processUser //The function that would do something with the user returned from the middleware if there are no errors
);
并在另一个文件中(你想要所有与auth相关的中间件,比如auth / middleware.js):
module.exports.getByToken = function (req, res, next)
{ var token_value = req.headers.authorization;
mongoose.model('tokens').findOne({ value: token_value}).exec(function (err, token)
{
if (err)
{
var error = new Error('couldn\'t find user of the given token');
//Log the error, if required
return res.status(500).send()
}
else if(token === null || !token) {
var error = new Error('couldn\'t find user of the given token');
//Log the error, if required
return res.status(404).send(error);
}
else
{ //here next refers to a function that accepts error and user as arguments and does some processing.
mongoose.model('users').find({ _id: token.user }).exec(next);
}
});
};