Explain Codes LogoExplain Codes Logo

Proper way to catch exception from JSON.parse

javascript
json-parsing
error-handling
best-practices
Alex KataevbyAlex Kataev·Mar 3, 2025
TLDR

For safe handling of JSON.parse, make use of a try-catch block. This ensures your application doesn't break down when encountering potential errors.

Example:

let data = '{"valid": true}'; try { data = JSON.parse(data); // Let's start the parsing party! } catch (e) { console.error("JSON Party Pooper:", e); // Uh-oh, the JSON parser had too much to drink }

This guarantees that invalid JSON inputs are smoothly dealt with by logging an error message instead of throwing a full-blown exception.

Strategies for different scenarios

When doping with JSON parsing, don't expect everything to run smoothly. Always be on the lookout for possible errors and respond accordingly.

Preemptive response validation

Check your HTTP status codes before attempting to parse any JSON data from a response. This helps avoid unnecessary parsing of responses like a 404 Not Found. Let's save the parsing party for valid responses!

function fetchAndParse(url) { return fetch(url) .then(response => { if (!response.ok) { throw new Error('HTTP Party Pooper detected'); } return response.json(); // One ticket to JSON party, please! }) .catch(error => { console.error("Fetch and parse error:", error); }); }

Better safe than sorry

Always ensure that your input string is valid before trying to parse it. A little caution can save you from a bunch of errors caused by your undefined, null or any other unwanted party crashers trying to ruin your JSON party.

function safeParse(input) { if (typeof input !== 'string') throw new Error('No gatecrashers allowed! Not a string.'); try { return JSON.parse(input); } catch (error) { console.error("Party foul:", error.message); // Shout out to the party foul! return null; } }

The Special Case of SyntaxError

Your JSON.parse might occasionally throw a SyntaxError. In such cases, it helps to have some additional logic laid out for easy debugging or notification.

try { data = JSON.parse(data); // JSON party going good... } catch (e) { if (e instanceof SyntaxError) { console.error("Party Fouler SyntaxError detected:", e.message); // Alert the JSON security! // Custom response to a SyntaxError } else { throw e; // For non-SyntaxErrors, send them to the command center } }

More parsing control with reviver function

The JSON.parse() function can take a reviver function as the second invitee - I mean, argument. This gives you more control over who gets into the parsing party.

JSON.parse(data, (key, value) => { // Make any necessary changes to your guests here return key === 'date' ? new Date(value) : value; });

Advanced error management strategies

Writing robust and maintainable applications require you to consider the following advanced management techniques when dealing with exceptions from JSON.parse.

Centralized error handling function

Consider encapsulating the parsing logic in a centralized function. It's like having a manager at your JSON party, ready to handle things when they get out of hand.

function parseJSON(input, fallback = {}) { try { return JSON.parse(input); // Hoping for a smooth party } catch (e) { console.error("Party Errored Out:", e); return fallback; // Always have a Plan B } }

Consistent data formats

Ensure consistency in your date format. It's like setting a drink limit at your JSON party. Any deviation can result in unforeseen after effects - or parsing failures in our case.

Handling multiline strings with backticks

Like how backticks (`) help handle someone who had too many spirits, they come in handy for multiline strings in your JSON parsing party too.

let jsonString = `{ "key": "value", "number": 123 }`;

Custom error flows

Sometimes, you need to throw a new Error in your catch block to maintain order at your JSON party - it's like having specialized bouncers for your party.

catch (e) { throw new Error("Calling in the JSON bouncers!", { cause: e }); }

Fallback plans

Always have a fallback. Return a value from your function - it could be the parsed JSON or a fallback. This keeps your function flexible and efficient, no matter the exceptions.