0

It does the job, but it feels ugly and repetitive. Any way to improve it? Also, is it considered good practice to use a try catch like this to check if a value is valid?

function readJson(key, fallback) {
  localStorage.getItem(key) ??
    localStorage.setItem(key, fallback);

  try {
    return JSON.parse(localStorage.getItem(key));
  } catch {
    localStorage.setItem(key, fallback);
    return JSON.parse(localStorage.getItem(key));
  }
}

try {
  // using hex2Rgb only to check if localStorage.getItem(hexColor) has valid value
  hex2Rgb(localStorage.getItem(hexColor));
  setColor(localStorage.getItem(hexColor));
} catch {
  setColor("#000000");
}
Richard
  • 64
  • 7

2 Answers2

0

It depends on the case. Here are some points to consider:

1 - Is there a way to validate without throwing an error?

If you don't have a function like JSON.isValid, I don't see how you would do that differently. But for hex2Rgb, I'm pretty sure you can create a function to check if the hex is a valid value.

2 - Follow your codebase pattern

Check if using try/catch for validation is common in your codebase, better to follow it. Given your question, I think this is not the case.

3 - Easier to read

For me and the teams I've worked with, using if/else makes the code easier to read... I would also consider including those checks in separate private functions with good names instead of documenting every if/else, or inline for default values:

String hexColor = isValid(hexColor) ? hexColor: DEFAULT_HEX_COLOR

Besides do not use bare excepts, better to be explicitly with which errors you are catching.

Juliano Negri
  • 299
  • 2
  • 9
0

I think it's highly subjective, personally I wouldn't consider validating a JSON with try/catch a bad practice.

There's a more in-depth discussion about JSON validations (with possible answers) here.

If anything, perhaps I would consider using a more intuitive boolean syntax:

function isValidJSON(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

if(isValidJson(localStorage.getItem(key)))
{
  /* Valid JSON */
}
else
{
  /* Not a valid JSON */
}
Jarmo T
  • 164
  • 4