Express 如何合并请求npm包中的错误?
到目前为止,我已经:Express 如何合并请求npm包中的错误?,express,refactoring,Express,Refactoring,到目前为止,我已经: request(opts, function(err, response, body) { var user; if (err) { throw err; } if (response.statusCode !== 200) { throw 'Invalid statusCode'; } if (body.status !== 'ok') { throw body.error; } return user = body
request(opts, function(err, response, body) {
var user;
if (err) {
throw err;
}
if (response.statusCode !== 200) {
throw 'Invalid statusCode';
}
if (body.status !== 'ok') {
throw body.error;
}
return user = body.user;
});
这似乎有点冗长,那么有没有办法整合这段代码?这并不是一个很大的改进(更像是code golf),但下面是一个使用短路逻辑运算符实现简洁Javascript的示例:
request(opts, function(err, response, body) {
err = err ||
(response.statusCode !== 200 && 'Invalid statusCode') ||
(body.status !== 'ok' && (body.error || 'not ok'));
if (err) throw err;
return body.user;
});
如果问题是在多个位置进行相同的错误处理,则另一种方法是编写一个包装器来为您合并错误:
function request_wrapped(opts, callback) {
request(opts, function(err, response, body) {
if (!err && response.statusCode !== 200) {
err = 'Invalid statusCode';
}
if (!err && body.status !== 'ok') {
err = body.error;
}
callback(err, response, body);
});
}
然后,您将调用request\u wrapped
而不是request
,只需检查回调中的err
参数,如下所示:
request_wrapped(opts, function(err, response, body) {
if (err) throw err;
return body.user;
});