【问题标题】:Removing duplicate error handling code Node.js删除重复的错误处理代码 Node.js
【发布时间】:2017-10-31 22:34:31
【问题描述】:

我的 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);

【问题讨论】:

  • 您能否准确指出,您想避免哪些重复项?
  • 你的意思是你在每个函数中'handleError'两次?
  • 你可以扔掉error 并抓住它。所以它会像:try { request(URL+'/olympic/2016/ranking/4', getRanking); } 捕捉(错误) { 控制台.log(错误); }
  • @Lazyexpert 我知道我们可以同时检查错误和 response.statusCode,然后调用 handleError。它将删除一些额外的行,除此之外我可以使代码更好

标签: javascript node.js error-handling callback


【解决方案1】:

你可以试试下面的代码:

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

【讨论】:

    【解决方案2】:

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

    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一个错误然后,你将能够@987654325 @它。

    希望对你有帮助,
    最好的问候

    【讨论】:

      【解决方案3】:

      创建一个函数handleResponse 并在该函数中写入response handling duplicated code

      使用给定的required parameters 调用function

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

      【讨论】:

        【解决方案4】:

        好的,只要没有人建议这样的优化,我会的。 而不是这样的块:

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

        【讨论】:

          【解决方案5】:

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2016-07-19
            • 2010-09-05
            • 2016-07-25
            • 1970-01-01
            • 2011-04-12
            • 1970-01-01
            相关资源
            最近更新 更多