Error Handling — try / catch
Bugs happen. Network requests fail. Users enter unexpected input. Error
handling is what separates fragile scripts from production-ready code.
JavaScript provides try, catch, finally,
and throw to intercept, respond to, and recover from errors — and
lets you define custom Error classes for domain-specific problems.
try / catch / finally block structure and when each part runs
throw and the Error constructor
TypeError, RangeError,
SyntaxError and more
Error subclasses for your own application errors
async/await and Promise chains
window.onerror and unhandledrejection
Why Error Handling Matters
Without proper error handling, a single unexpected failure can silently crash your entire application — leaving users with a broken page and no feedback. Good error handling means your app fails gracefully: it catches the problem, logs it, shows a helpful message, and keeps running.
- Uncaught errors crash the entire JS execution thread
- Users see nothing — white screen or frozen UI
- No logging — hard to debug in production
- Async failures silently disappear (unhandled rejections)
- Cannot distinguish different error types or respond accordingly
- App continues running after handled errors
- Users see friendly, actionable error messages
- Errors are logged for monitoring and debugging
- Async errors are always caught with try/catch or .catch()
- Custom Error classes enable typed, recoverable errors
The try / catch / finally Structure
JavaScript's error handling is built on three keywords that work together.
Code that might throw goes inside try.
If it throws, execution jumps to catch, which
receives the error object. finally always runs —
whether an error occurred or not — perfect for cleanup work.
catch is skipped entirely and execution
continues after the block (or in finally).
err.message, err.name, err.stack.
You can re-throw if you can't handle the error here.
try succeeds or
after catch handles an error. Use it to close connections,
hide loading spinners, or release resources. Optional — can be omitted.
new Error("message") (or a subclass) so the
catch block gets a proper error object with a stack trace.
// ── Basic structure ───────────────────────────────────────
try {
const data = JSON.parse('{ bad json }'); // throws SyntaxError
console.log(data.name); // ← never reached
} catch (err) {
console.error("Caught:", err.name); // "SyntaxError"
console.error("Message:", err.message); // "Unexpected token b..."
console.error("Stack:", err.stack); // full stack trace
} finally {
console.log("This always runs"); // cleanup here
}
// ── finally for cleanup — loading spinner example ─────────
async function loadData() {
showSpinner(); // start loading UI
try {
const res = await fetch("/api/data");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
renderData(data);
} catch (err) {
showErrorBanner(err.message);
} finally {
hideSpinner(); // always hide — whether success or error
}
}
// ── catch is optional if you only need finally ────────────
try {
riskyOperation();
} finally {
cleanup(); // runs even if error propagates upward
}The throw Statement
throw lets you raise your own errors — enforcing
preconditions, signalling invalid input, or converting low-level failures into
meaningful domain errors. You can technically throw any value, but
always throw an Error object so the receiver gets
a .message, .name, and stack trace.
throw new Error("msg") is executedtry block —
searching up through every caller in the stack.try/catch found — error is caught
catch block runs with the error object.
finally runs after, then execution continues normally.
// ── Validate input — throw on bad data ────────────────────
function divide(a, b) {
if (typeof a !== "number" || typeof b !== "number") {
throw new TypeError("Both arguments must be numbers");
}
if (b === 0) {
throw new RangeError("Cannot divide by zero");
}
return a / b;
}
try {
console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // throws RangeError
} catch (err) {
console.error(err.name, err.message); // RangeError: Cannot divide by zero
}
// ── Re-throwing — handle only what you can ────────────────
function processData(raw) {
try {
return JSON.parse(raw);
} catch (err) {
if (err instanceof SyntaxError) {
throw new Error(`Invalid JSON input: ${err.message}`); // wrap with context
}
throw err; // re-throw unexpected errors unchanged
}
}Built-in Error Types
JavaScript ships with several specialised Error
subclasses. Use instanceof inside
catch to handle each type differently,
or check err.name as a string comparison.
null or undefined.
toFixed() argument.
console.log(foo)
when foo was never defined.JSON.parse() or eval() with bad input.
decodeURIComponent().
eval().
Promise.any() when
all promises reject.try {
riskyOperation();
} catch (err) {
if (err instanceof TypeError) {
console.error("Type problem:", err.message);
// e.g. fix the type and retry
} else if (err instanceof RangeError) {
console.error("Value out of range:", err.message);
} else if (err instanceof SyntaxError) {
console.error("Malformed data — cannot parse");
} else if (err instanceof ReferenceError) {
console.error("Undefined variable:", err.message);
} else {
throw err; // unknown — re-throw for the caller
}
}
// ── Error properties every error object has ───────────────
const err = new TypeError("Expected a string");
console.log(err.name); // "TypeError"
console.log(err.message); // "Expected a string"
console.log(err.stack); // stack trace string (V8/Node.js)Custom Error Classes
For real applications you'll want to define your own error types — so callers can
use instanceof to distinguish an
AuthError from a
NetworkError from a
ValidationError.
Extend the built-in Error class and always call
super(message) in the constructor.
// ── Base application error ────────────────────────────────
class AppError extends Error {
constructor(message, code) {
super(message); // sets .message and .stack
this.name = "AppError";
this.code = code; // custom property
}
}
// ── Domain-specific subclasses ────────────────────────────
class ValidationError extends AppError {
constructor(field, message) {
super(message, "VALIDATION_ERROR");
this.name = "ValidationError";
this.field = field; // which field failed
}
}
class AuthError extends AppError {
constructor(message) {
super(message, "AUTH_ERROR");
this.name = "AuthError";
}
}
class NetworkError extends AppError {
constructor(message, status) {
super(message, "NETWORK_ERROR");
this.name = "NetworkError";
this.status = status; // HTTP status code
}
}
// ── Using custom errors ───────────────────────────────────
async function login(email, password) {
if (!email.includes("@")) {
throw new ValidationError("email", "Invalid email address");
}
const res = await fetch("/api/login", {
method: "POST",
body: JSON.stringify({ email, password }),
headers: { "Content-Type": "application/json" }
});
if (res.status === 401) throw new AuthError("Invalid credentials");
if (!res.ok) throw new NetworkError("Server error", res.status);
return res.json();
}
// ── Typed catch block ─────────────────────────────────────
try {
await login("bad-email", "pass");
} catch (err) {
if (err instanceof ValidationError) {
highlightField(err.field, err.message);
} else if (err instanceof AuthError) {
showToast("Wrong email or password");
} else if (err instanceof NetworkError) {
showToast(`Server error (${err.status})`);
} else {
throw err; // unexpected — propagate
}
}Error Handling in async / await & Promises
Errors in asynchronous code need their own strategies.
With async/await, wrap the entire async body in
try/catch — it catches both synchronous throws
and rejected Promises. With .then() chains, always
end with .catch(). An unhandled Promise rejection
is a silent bug — always handle it.
// ── async/await — try/catch is the cleanest approach ──────
async function fetchUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new NetworkError("Failed to fetch user", res.status);
const user = await res.json();
return user;
} catch (err) {
logError(err); // send to monitoring service
throw err; // re-throw for the caller to handle UI
}
}
// ── Promise chain — always attach .catch() ────────────────
fetch("/api/data")
.then(res => { if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.json(); })
.then(data => renderData(data))
.catch(err => showError(err.message)); // catches any throw above
// ── Danger: swallowing errors silently ────────────────────
async function badPattern() {
try {
await doSomething();
} catch (err) {
// ❌ empty catch — error is silently ignored!
}
}
// ── Better pattern: at minimum, log the error ─────────────
async function goodPattern() {
try {
await doSomething();
} catch (err) {
console.error("[goodPattern] unexpected error:", err); // ✅ at minimum log
throw err; // and re-throw for caller
}
}Global Error Handlers
Even with careful local error handling, some errors slip through. Register global handlers as a safety net — to log unexpected errors to a monitoring service (e.g. Sentry) before the user sees a broken page. These do not replace proper local handling — they are the last line of defence.
// ── window.onerror — catches synchronous uncaught errors ──
window.onerror = function(message, source, lineno, colno, error) {
console.error("Uncaught error:", { message, source, lineno, error });
sendToMonitoring({ message, source, lineno, stack: error?.stack });
return true; // prevents browser's default error UI
};
// ── unhandledrejection — catches unhandled Promise rejections
window.addEventListener("unhandledrejection", (event) => {
console.error("Unhandled Promise rejection:", event.reason);
sendToMonitoring({ type: "unhandledrejection", reason: event.reason });
event.preventDefault(); // suppresses console warning
});
// ── rejectionhandled — fires when a rejection IS later handled
window.addEventListener("rejectionhandled", (event) => {
console.log("Previously unhandled rejection is now handled");
});
// ── Node.js equivalents ───────────────────────────────────
process.on("uncaughtException", (err) => {
console.error("Uncaught exception:", err);
process.exit(1); // must exit — process is in undefined state
});
process.on("unhandledRejection", (reason, promise) => {
console.error("Unhandled rejection at:", promise, "reason:", reason);
});Quick Reference — Error Object Properties & Patterns
| Property / Pattern | Type | Description |
|---|---|---|
| err.name | string | Error type name — "TypeError", "RangeError", "ValidationError", etc. |
| err.message | string | Human-readable description passed to the Error constructor |
| err.stack | string | Full stack trace string — invaluable for debugging (V8 / Node.js) |
| err.cause | any | ES2022 — wrap an original error:
new Error("msg", { cause: originalErr })
|
| err instanceof Error | boolean | Checks error type — works across custom subclasses too |
| throw new Error(msg) | — | Always use Error objects — never throw strings or plain objects |
| try / catch / finally | — | Core block structure — finally runs even if catch
re-throws |
| .catch(handler) | Promise | Required at the end of every Promise chain — never leave a chain without it |
| unhandledrejection | event | Global safety net for Promise rejections — use for monitoring/logging only |
| Empty catch {} | anti-pattern | Never silently swallow errors — at minimum console.error(err) or
re-throw |
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.