删除重复的错误处理代码Node.js

时间:2017-05-31 08:21:31

标签: javascript node.js error-handling callback

我的Node.js代码中有重复的错误处理代码,如何才能更好地摆脱重复的代码。我特别想询问有关这种回调方式的错误处理,而不是Promise方式。

var request = require('request');
var URL = 'http://localhost:3000';

var getRanking = function get_rank(error, response, body) {
   if (error) {
        handleError(error);
   } else {         
       if (response.statusCode != 200) {
          handleError(response);
       } else {        
          console.log('Response 1 ' + body);
          request(URL + '/iso/country/' + JSON.parse(body).Country, getISO);
       }
   }
}

var getISO = function get_iso(error, response, body) {
    if (error) {
         handleError(error);          
    } else {
        if (response.statusCode != 200) {
             handleError(response)
        } else {
             console.log("Response 2 "+body);
             request(URL+'/olympic/2016/medal/'+JSON.parse(body).iso,getMedalCount);
        }
    } 
}

var getMedalCount = function get_medal_count(error, response, body) {
    if (error) {
       handleError(error);
    } else {
       if (response.statusCode != 200) {
           handleError(response);
       } else {        
           console.log("Response 3 " + body);
       }
    }  
}

function handleError(err) {
   console.log('Error ' + JSON.stringify(err))
}

request(URL+'/olympic/2016/ranking/4', getRanking);

5 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

var request = require('request');
var URL = 'http://localhost:3000';

var getRanking = function get_rank(error, response, body) {
   if (error) {
        throw error;
   }
   if (response.statusCode != 200) {
        throw new Error(response);
   }      
   console.log('Response 1 ' + body);
   request(URL + '/iso/country/' + JSON.parse(body).Country, getISO);
}

var getISO = function get_iso(error, response, body) {
    if (error) {
        throw error;
    }
    if (response.statusCode != 200) {
        throw new Error(response);
    }
    console.log("Response 2 "+body);
    request(URL+'/olympic/2016/medal/'+JSON.parse(body).iso,getMedalCount);
    } 
}

var getMedalCount = function get_medal_count(error, response, body) {
    if (error) {
        throw error;
    }        
    if (response.statusCode != 200) {
       throw new Error(response);
        return;
   }
   console.log("Response 3 " + body);
}

try {
    request(URL+'/olympic/2016/ranking/4', getRanking);
} catch(ex) {
    console.log(ex);
}

答案 1 :(得分:0)

缩短代码的最简单方法可能如下:

function handleError(err, res) {
   if(err){
     console.log('Error '+JSON.stringify(err));
     return false;
   } else if(res.statusCode != 200) {
     console.log('Error '+JSON.stringify(res));
     return false;
   } else {
     return true;
   }
}

// and then, use it in your functions like that : 
var getRanking = function get_rank(error,response,body) {
  if (handleError(err, res)) { // if there is no error, do your stuff   
     console.log("Response 1 "+body);
     request(URL+'/iso/country/'+JSON.parse(body).Country,getISO);
   }
}

但我认为这不适合JS,因为JS可以用作函数式编程语言(更好),这种方法看起来更具程序性(比如C语言)。
因此,在我看来,以下解决方案是正确的:

function handleError(successFunc) {
  return function (error, response, body) { 
    if (error) {
      throw new Error(error);
    } else if(response.statusCode != 200) {
      throw new Error(response);
    } else {
      successFunc(response);
    }
  }
}

// then, just pass your successFunc to your error handler :


var getRanking = function (response) {
  // do your success stuff.
}
try {
  request(URL+'/olympic/2016/ranking/4', handleError(getRanking));
} catch (e) {
  // catch your error here
}

如果您的请求成功,将执行getRanking,如果失败,则会记录并抛出错误。

使用此解决方案,您可以将任何函数传递给错误处理程序,如果请求成功,将使用它,如果请求失败,错误处理程序将throw错误然后,您将能够catch它。

希望它有所帮助,
最好的问候

答案 2 :(得分:0)

创建一个功能handleResponse并在该功能中写下response handling duplicated code

functionrequired parameters一起称为

var request = require('request');
var URL = 'http://localhost:3000';

var getRanking = function get_rank(error, response, body) {
   handleResponse(error, response, body, 'getISO');
}

var getISO = function get_iso(error, response, body) {
    handleResponse(error, response, body, 'getMedalCount');
}

var getMedalCount = function get_medal_count(error, response, body) {
    handleResponse(error, response, body null);
}

function handleResponse(error, response, body, url) {
   if (error) {
        handleError(error);
   } else {         
       if (response.statusCode != 200) {
          handleError(response);
       } else {
            if(url == 'getISO')        
            {
                request(URL + '/iso/country/' + JSON.parse(body).Country, getISO);
            }
            else if(url == 'getMedalCount')
            {
                request(URL+'/olympic/2016/medal/'+JSON.parse(body).iso,getMedalCount);
            }
       }
   }
}

function handleError(err) {
   console.log('Error ' + JSON.stringify(err))
}

request(URL+'/olympic/2016/ranking/4', getRanking);

答案 3 :(得分:0)

好的,就没有人提出这样的优化,我会的。 而不是这样的阻止:

if (error) {
  handleError(error);
} else {
  if (response.statusCode != 200) {
    handleError(response);
  } else {        
    console.log("Response 3 " + body);
  }
}

你可以这样做:

if (error || response.statusCode != 200) handlerError(error || response);
else console.log("Response 3 " + body);

答案 4 :(得分:0)

您可以使用以下代码来处理响应。

var request = require('request');
var URL     = "http://localhost:3000";


var getRanking = function get_rank (body) {
    console.log("Response 1 " + body);
    request(URL + '/iso/country/' + JSON.parse(body).Country, handleResponse.bind(null, getISO));
}

var getISO = function get_iso (body) {
    console.log("Response 2 " + body);
    request(URL + '/olympic/2016/medal/' + JSON.parse(body).iso, handleResponse.bind(null, getMedalCount));
}


var getMedalCount = function get_medal_count (body) {
    console.log("Response 3 " + body);
}

function handleResponse (callback, error, response, body) {
    console.log(error, response, body, callback)
    if (error || response.statusCode != 200) {
        console.log('Error ' + JSON.stringify(error))
    }
    else {
        callback(body);
    }
}

request(URL + '/olympic/2016/ranking/4', handleResponse.bind(null, getRanking));