I am trying to create a scenario where if endpoint doesn’t exists, function still returns a value.
When the endpoint exists, I get a value, no problem.
var main = function(){
json_url = "http://ergast.com/api/f1/current/next.json";
xhr = new XMLHttpRequest();
xhr.open("GET", json_url, false);
xhr.send(null);
weather = JSON.parse(xhr.responseText);
let race = " ";
if (weather.MRData.RaceTable.Races[0].Sprint.date === undefined) {
race = " ";
}
else {
race = weather.MRData.RaceTable.Races[0].Sprint.date;
}
return race;
}
I get the following result
2022-07-09
But in case the endpoint doesn’t exists, I get a error.
var main = function(){
json_url = "http://ergast.com/api/f1/current/last.json";
xhr = new XMLHttpRequest();
xhr.open("GET", json_url, false);
xhr.send(null);
weather = JSON.parse(xhr.responseText);
let race = " ";
if (weather.MRData.RaceTable.Races[0].Sprint.date === undefined) {
race = " ";
}
else {
race = weather.MRData.RaceTable.Races[0].Sprint.date;
}
return race;
}
How can I rectify this. Do I have to assign something other than undefined in this case.