Reputation: 93
i made this function that makes a request to the API based on the past parameters, only if it returns an error i want a NEW REQUEST to be made only by changing the value of the URL that i pass, removing a parameter, it's possible? Below is what i tried but failed
try {
const URL = 'http://api.evoximages.com/api/v1/vehicles?make='+make+'&model='+model+'&year='+year+'&pid=2&ptid=41&body='+body;
let res = await axios.get(URL);
if (res.data.statusCode == 404) {
URL = 'http://api.evoximages.com/api/v1/vehicles?make='+make+'&model='+model+'&year='+year+'&pid=2&ptid=41';
res = await axios.get(URL);
return res.data.data;
} else {
return res.data.data;
}
} catch (err) {
return err;
}
I realized that I can't get the statusCode because they are falling in Catch(err), so how can I do to make a new request if the first is not accepted?
SOLUTION:
try {
const URL = 'http://api.evoximages.com/api/v1/vehicles?make='+make+'&model='+model+'&year='+year+'&pid=2&ptid=41&body='+body;
let res = await axios.get(URL);
return res.data.data;
} catch (err) {
try {
// New request
const URL = 'http://api.evoximages.com/api/v1/vehicles?make='+make+'&model='+model+'&year='+year+'&pid=2&ptid=41';
let res = await axios.get(URL);
return res.data.data;
} catch (err) {
return err;
}
}
Upvotes: 1
Views: 501
Reputation: 3405
If it only what you describe of one request being failed you want the second to start then call the second one inside the first catch
try {
const URL = 'http://api.evoximages.com/api/v1/vehicles?make=' + make + '&model=' + model + '&year=' + year + '&pid=2&ptid=41&body=' + body;
let res = await axios.get(URL);
return res.data.data;
} catch (err) {
console.error(err);
try {
URL = 'http://api.evoximages.com/api/v1/vehicles?make=' + make + '&model=' + model + '&year=' + year + '&pid=2&ptid=41';
res = await axios.get(URL);
return res.data.data;
}
catch(error){
console.error(error);
}
}
if you have many urls, and you want to keep requesting if the first failed and keep goind until the end you can do something like this
const urls = [
'http://api.evoximages.com/api/v1/vehicles?make=' + make + '&model=' + model + '&year=' + year + '&pid=2&ptid=41&body=' + body,
'http://api.evoximages.com/api/v1/vehicles?make=' + make + '&model=' + model + '&year=' + year + '&pid=2&ptid=41',
'any more urls...'
];
async function callingUrlsInSequence(urls) {
let i = 0;
while (i < urls.length) {
const url = urls[i];
try {
const response = await axios.get(url);
// break the loop and return from function if the request succeed
return response;
// otherwise we keep looping...
} catch (error) {
console.error('The Url: ' + url + ' Failed!')
continue;
} finally {
i++;
}
}
}
Upvotes: 1