[英]Same error response for all fails with request.js
I'm using request.js for node.js. 我正在将request.js用于node.js。
I was wondering what would be the best way to return the same error for all failed responses. 我想知道对于所有失败的响应返回相同错误的最佳方法是什么。
Right now I'm returning the following json object for all fails: 现在,我为所有失败返回以下json对象:
res.json({success: false, message: 'An error has occurred'});
But I'm doing it per request, in each call. 但我在每个请求中都按请求执行。 Like the following:
如下所示:
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);
}
});
How can I deal with it in only one single place? 我如何只在一个地方处理它? Does request provides a way to do it?
请求是否提供了一种方法? Or should I go for something like:
或者我应该去做类似的事情:
var failResponse ={success: false, message: 'An error has occurred'};
And then using this in every request: 然后在每个请求中使用它:
res.json(failResponse);
Would something like this work for you? 这样的事情对您有用吗?
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)
})
});
Or, going by your own suggestion (with a little clean up) you could do the following: 或者,按照您自己的建议(稍作清理),您可以执行以下操作:
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.