What do you think of the following code snippet to catch crashes because of bad types

Hi, I'm getting fed up with crashes because of property type change between app release or bad data return in a JSON object from makeWebRequest, so I wrote the following two functions to deal with that (I have one for each main type (number, float, string and boolean). How would you improve upon it? I tried to make it generic instead of having one set per type I'm validating against but was unable to find a way. The validate can even handle dictionaries or arrays passed at them instead of a number (they don't have a toNumber method). In that case, it returns the default value.

function getNumberProperty(key, defaultValue) {
	var value;

	try {
		value = Properties.getValue(key);
	}
	catch (e) {
		value = defaultValue;
	}

	return validateNumber(value, defaultValue);
}

function validateNumber(value, defaultValue) {
	if (value == null || !(value has :toNumber)) {
		value = defaultValue;
	} else if (!(value instanceof Lang.Number)) {
		try {
			value = value.toNumber();
		}
		catch (e) {
			value = defaultValue;
		}
	}
	if (value == null) {
		value = defaultValue;
	}
	return value;
}

For boolean, it's a bit different since there is no toBoolean method but Numbers are accepted so this seems to work with all the cases I threw at it

function validateBoolean(value, defaultValue) {
	if (value == null) {
		value = defaultValue;
	} else if ((value instanceof Lang.Boolean) || (value instanceof Lang.Number)) {
		try {
			if (value) {
				value = true;
			}
			else {
				value = false;
			}
		}
		catch (e) {
			value = defaultValue;
		}
	}
	else {
		value = defaultValue;
	}

	if (value == null) {
		value = defaultValue;
	}
	return value;
}

The 'if' inside the 'try' could be an overkill though.

  • Ok, so this version will try to set the property to its default value if it threw an exception reading it (whatever the exception is) so next time it doesn't throw one. It also checks for exception writing it, in case it's from a background process for example. Am I going too deep with this, or is it better that way? I wish CIQ could handle that by itself, but it is what it is...

    function getNumberProperty(key, defaultValue) {
    	var value;
    	var exception;
    
    	try {
    		exception = false;
    		value = Properties.getValue(key);
    	}
    	catch (e) {
    		exception = true;
    		value = defaultValue;
    	}
    
    	if (exception) {
    		try {
    			Properties.setValue(key, defaultValue);
    		}
    		catch (e) {
    		}
    	}
    	return validateNumber(value, defaultValue);
    }
    

    Not sure if I can have a try in a catch so that's why that 'exception' variable.

    Edit: But why does it crash for some and not others and why am I unable to reproduce it?, I created a "TestProperty" and without going into Settings, I ran the code simulating my Venu2 and it read its default value just fine, no exception thrown,