【问题标题】:Same error response for all fails with request.js使用 request.js 对所有失败的相同错误响应
【发布时间】:2016-03-18 12:12:42
【问题描述】:

我将 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);
        }
    });

我怎样才能只在一个地方处理它? request 是否提供了一种方法来做到这一点? 或者我应该选择类似的东西:

var failResponse ={success: false, message: 'An error has occurred'};

然后在每个请求中使用它:

res.json(failResponse);

【问题讨论】:

  • 你的else 声明也总是一样吗?

标签: node.js express node-request


【解决方案1】:

这样的东西对你有用吗?

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));
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多