iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Errors

JavaScript signals problems by throwing values — usually Error objects. try…catch handles them; finally runs cleanup either way.

Built-in error types

TypeThrown when…
ErrorGeneric — the base class.
TypeErrorOperation on the wrong type (e.g. calling a non-function).
ReferenceErrorAccessing a name that doesn't exist.
SyntaxErrorCode that can't be parsed.
RangeErrorNumber out of valid range.
URIErrorInvalid URI in encode/decode.

Try / catch / finally

JS
try {
  const data = JSON.parse(input);
  process(data);
} catch (err) {
  console.error("Parse failed:", err.message);
} finally {
  cleanup();        // always runs, even if the try returned
}

Throwing your own errors

JS
// Throw a built-in Error
if (!user) throw new Error("User not found");

// Custom class — adds extra fields
class HttpError extends Error {
  constructor(message, status) {
    super(message);
    this.name   = "HttpError";
    this.status = status;
  }
}

throw new HttpError("Forbidden", 403);

Async errors

JS
// try/catch around await works just like sync
async function loadUser(id) {
  try {
    const res = await fetch(`/api/users/${id}`);
    if (!res.ok) throw new HttpError("Failed", res.status);
    return res.json();
  } catch (err) {
    console.error(err);
    throw err;     // re-throw so the caller can decide
  }
}
Tip: Throw early, catch where you can recover. Never swallow errors silently — at minimum log them; ideally surface them to the user.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Errors!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Run cleanup whether the try succeeded or threw.

try { run(); } catch (e) { log(e); } { cleanup(); }

Test yourself

Q1. The base class of all built-in errors is…
Q2. Code that should always run (cleanup) goes in…
Q3. Custom error classes typically…

Discussion

Loading…