gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:49:43 25 4
gpt4 key购买 nike

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

最佳答案

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

按照给定的function调用该required 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);

关于javascript - 删除重复的错误处理代码Node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44279385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com