Μετάβαση στο κύριο περιεχόμενο
← ⚡ JavaScript & the browser·Ενότητα C7 · Μάθημα 5
ΕργασίαDefine class TooSmallError extends Error and class TooBigError extends Error. Write checkAge(n) that throws TooSmallError if n < 0, TooBigError if n > 120, returns n otherwise. Loop over [-1, 50, 200, 30], call checkAge in try/catch, narrow with instanceof, log: 'small' / 'big' / value / 'unknown'.

Narrowing errors with instanceof

125 XP8 min
Θεωρία

Different errors, different handlers

A catch block gets a single err variable but errors come in many shapes. Use instanceof to branch:

try {
  await fetchUser(id);
} catch (err) {
  if (err instanceof NotFoundError) {
    return null;                  // silently treat 404 as no result
  }
  if (err instanceof RateLimitError) {
    await sleep(err.retryAfter * 1000);
    return fetchUser(id);          // retry once
  }
  throw err;                       // unknown — let it bubble
}

Always end with a re-throw

If you didn't handle the error type, you DON'T know what it is. throw err at the bottom of every catch is the safe default. Swallowing errors silently is one of the most common bugs in JS code.

TypeScript-aware editors

In a .js project with JSDoc types, editors narrow the type inside each instanceof branch — same intellisense as TypeScript. Lesson C5-04 is the foundation.

🔒

Εγγράψου για να αρχίσεις να προγραμματίζεις

Η θεωρία είναι ανοιχτή για όλους. Ο επεξεργαστής, η ζωντανή προεπισκόπηση και ο έλεγχος ξεκλειδώνουν με 7-ήμερη δωρεάν δοκιμή — απαιτείται κάρτα.

Εγγραφή — δωρεάν δοκιμή →

Τα πρώτα 10 μαθήματα κάθε διαδρομής είναι δωρεάν. Δεν χρειάζεται κάρτα.

← ΠροηγούμενοΕπόμενο μάθημα →

Μια συμβουλή Python ή web την ημέρα — με email

Σύντομο, γραμμένο στο χέρι, χωρίς spam. Διαγραφή με ένα κλικ.