javascript / beginner
Snippet
Safely Parsing Local Storage JSON with Fallback Error Handling in Svelte
Reading and deserializing JSON from external sources such as browser storage can throw runtime exceptions if the data format is malformed. Wrapping JSON.parse in a try-catch block provides fault tolerance and allows your Svelte state to maintain a valid fallback object.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
<script>let profile = { name: 'Guest' };try {const raw = localStorage.getItem('profile');if (raw) profile = JSON.parse(raw);} catch (err) {console.error('Failed to parse profile payload:', err);}</script><h1>Welcome, {profile.name}</h1>
svelte
Breakdown
1
let profile = { name: 'Guest' };
Initializes default fallback state to ensure safe rendering if storage parsing fails.
2
try {
Starts the guarded execution block to intercept syntax errors thrown during JSON deserialization.
3
const raw = localStorage.getItem('profile');
Retrieves the raw JSON string value stored under the 'profile' key.
4
if (raw) profile = JSON.parse(raw);
Parses the stored text into an object only if non-null data was found.
5
} catch (err) {
Catches any JSON parse syntax errors and prevents application crashes.