[英]Same error response for all fails with request.js
我正在将request.js用于node.js。
我想知道对于所有失败的响应返回相同错误的最佳方法是什么。
现在,我为所有失败返回以下json对象:
res.json({success: false, message: 'An error has occurred'});
但我在每个请求中都按请求执行。 如下所示:
request.post({
uri: res.locals.baseUrl + 'myAction',
qs: params
}, function (error, response, body) {
if (error || response.statusCode != 200) {
res.json({success: false, message: 'An error has occurred'});
}else{
var data = JSON.parse(body);
res.json(data);
}
});
我如何只在一个地方处理它? 请求是否提供了一种方法? 或者我应该去做类似的事情:
var failResponse ={success: false, message: 'An error has occurred'};
然后在每个请求中使用它:
res.json(failResponse);
这样的事情对您有用吗?
function sendResp(error, response, body, callback) {
if (error || response.statusCode != 200) {
// Error occurred
return callback(true, {
success: false,
message: 'An error has occurred'
})
}
// No errors, just send the body
callback(null, JSON.parse(body))
}
request.post({
uri: res.locals.baseUrl + 'myAction',
qs: params
}, function(error, response, body) {
sendResp(error, response, body, function(error, msg){
// If an error occured, return an error
if(error) return res.json(msg)
// Otherwise, display the response body
res.json(msg)
})
});
或者,按照您自己的建议(稍作清理),您可以执行以下操作:
var failResponse = {
success: false,
message: 'An error has occurred'
};
request.post({
uri: res.locals.baseUrl + 'myAction',
qs: params
}, function(error, response, body) {
// If there is an error, show it
if (error || response.statusCode != 200) return res.json(failResponse);
// No error, show response body
res.json(JSON.parse(body));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.