javascript / beginner
Snippet
Safely Parsing Stored JSON Strings Using Try-Catch Blocks
When parsing dynamic string inputs like localStorage values with `JSON.parse()`, invalid syntax causes JavaScript to throw runtime exceptions. Wrapping the operation in a `try...catch` block intercepts parsing errors cleanly, allowing your application to supply reliable fallback values without crashing the user interface.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
function loadSavedSettings(jsonString) {try {const parsed = JSON.parse(jsonString);return parsed;} catch (error) {console.error('Failed to parse settings JSON:', error);return { theme: 'light', notifications: true };}}
svelte
Breakdown
1
function loadSavedSettings(jsonString) {
Declares a helper function accepting a raw serialized JSON string as input.
2
try {
Initiates a guarded code block where potential runtime exceptions will be caught.
3
const parsed = JSON.parse(jsonString);
Attempts to deserialize the JSON string into a native JavaScript object.
4
return parsed;
Returns the successfully parsed object when no exceptions occur.
5
} catch (error) {
Executes if `JSON.parse` throws a SyntaxError due to malformed or corrupted data.
6
console.error('Failed to parse settings JSON:', error);
Logs error diagnostics to the developer console for debugging purposes.
7
return { theme: 'light', notifications: true };
Supplies a safe default configuration object so dependent components stay resilient.
8
}
Concludes the error handling block.
9
}
Closes the function definition.