JS Errors
JavaScript signals problems by throwing values — usually Error objects. try…catch handles them; finally runs cleanup either way.
Built-in error types
| Type | Thrown when… |
|---|---|
Error | Generic — the base class. |
TypeError | Operation on the wrong type (e.g. calling a non-function). |
ReferenceError | Accessing a name that doesn't exist. |
SyntaxError | Code that can't be parsed. |
RangeError | Number out of valid range. |
URIError | Invalid 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(); }
Seven letters.
Discussion
Loading…