Suppose we have a function that accepts JSON with an array of data as a parameter and save each array element to a local storage:
function saveData(json) {
let arr = JSON.parse(json);
for (let i = 0; i < arr.length; i++) {
localStorage.setItem(i, arr[i]);
}
}
In this function, an exception can occur in two places: when parsing JSON and when trying to save data to a local storage.
Let, for example, as error handling, we decided to display some message about problems:
try {
saveData('{1,2,3,4,5}');
} catch (error) {
alert('any problems');
}
Our message is, of course, good, but it doesn't differentiate the problems that have arisen. It would be more logical to display a message about what kind of problem arose.
To do this, we will distinguish by name the errors that have occurred:
try {
saveData('{1,2,3,4,5}');
} catch (error) {
if (error.name == 'QuotaExceededError') {
alert('ran out of storage space');
}
if (error.name == 'SyntaxError') {
alert('incorrect JSON');
}
}
Copy the code of my saveData
function, and then, without looking
into my code, implement the error
handling I described.
On purpose, one by one, create
exceptions that may occur in
the saveData
function.