Reputation: 363
Assuming both tries fail, url returns as undefined and console.log doesn't execute in this case. Is there a problem with my stacking of try-catch clauses, or with the scope of the url variable?
I am using try-catch because in my context url1,2, default may not be available.
getURL = function()
{
var url;
try{
url=data.url1;
}
catch(err1)
{
try{
url=data.url2;
}
catch(err2)
{
console.log("Fetching default url");
url=data.defaulturl;
}
}
finally
{
//do something with url
}
}
I tried using an if-else-if structure, but it returns error if data.url 1/2/default is unavailable.
if('String' === typeof data.url1)
{
}
else if(check for url 2/default etc.){...}
Upvotes: 0
Views: 5069
Reputation: 1229
My last attempt to reinvent the question... But if all the keys are undefined or URL loadings are unsuccessful, there are NO success at all.
getURL = function() {
var localData = data || {};
var keys = ['url1', 'url2', 'defaulturl'];
var success = false;
var currentKey;
while (!success && keys.length > 0) {
currentKey = keys.shift();
if (localData.hasOwnProperty(currentKey)
&& 'string' === typeof localData[currentKey]) {
try {
url = localData[currentKey];
// Url loading code may throws an exception,
// or you can throw it below by hands if needed
// Emulate loading result...
if (Math.random() > .5) {
throw 'Error in ' + localData[currentKey] + ' loading';
}
success = true;
} catch(exception) {
// Logging or something else here
console.log(exception.toString());
}
}
}
}
Upvotes: 2