Przejdź do treści głównej
← ⚡ JavaScript & the browser·Moduł C7 · Lekcja 9
ZadanieWrite safeParse(str, fallback) that returns JSON.parse(str) on success, fallback on SyntaxError, re-throws other errors. Test with safeParse('{"a":1}'), safeParse('not json', 'bad'), safeParse('[1,2,3]', []). Log JSON.stringify of each result.

Defensive parsing of unknown input

125 XP9 min
Teoria

JSON.parse can throw

JSON.parse(str) throws SyntaxError on any non-JSON input. If str comes from a URL, localStorage, or any external source, you must guard.

function safeParse(str, fallback = null) {
  try {
    return JSON.parse(str);
  } catch (err) {
    if (err instanceof SyntaxError) return fallback;
    throw err;  // unknown error — re-throw
  }
}

safeParse('{"a":1}');         // { a: 1 }
safeParse("not json", []);    // []

The pattern

Functions consuming external data should:

  1. Accept a default for the failure case.
  2. Catch only the EXPECTED error type.
  3. Re-throw anything else.

This shape pops up everywhere — query string parsing, file uploads, IPC messages, webhook bodies. Same code.

Defensive but not paranoid

Don't wrap every operation in try/catch — that's noise. Wrap operations that CAN fail at known boundaries: network, user input, file I/O, third-party libs. Internal code should trust itself.

🔒

Zarejestruj się, aby zacząć kodować

Teoria jest dostępna dla każdego. Edytor, podgląd na żywo i check odblokowują się z 7-dniowym darmowym okresem próbnym — wymagana karta, anuluj w dowolnym momencie.

Zarejestruj się — darmowy okres próbny →

Pierwsze 10 lekcji w każdej ścieżce jest darmowych. Karta nie jest wymagana.

← PoprzedniaNastępna lekcja →

Codziennie jedna wskazówka Python lub web — na maila

Krótko, ręcznie pisane, bez spamu. Wypisanie w jedno kliknięcie.