JavaScript · Lesson 10
Errors and Error Handling
How throw, try/catch/finally and Error objects really work in JavaScript, how to design error classes with causes, how to handle values you can't trust, and when to return a result object instead of throwing.
In short
throwunwinds to the nearestcatch- Throw
Errorobjects; treat caught values as unknown - Custom classes: set
name, add properties, pass{ cause } finallyis for cleanup; neverreturnfrom it- Rethrow what you can't handle; results for expected failures
Every app fails somewhere: a request times out, a user types a date backwards, a config file is missing a field. What separates solid code from fragile code is what happens next. Does the user see a useful message? Does the log say what failed and why? Does the database connection still get closed?
JavaScript's error handling looks like C#'s or Java's, with throw, try, catch and finally. But
the details differ in ways that matter: you can throw anything, there's one catch with no type filter,
finally can swallow errors, and errors don't serialise to JSON. This lesson covers the mechanics, then
the patterns you'll use at work.
Every snippet has a ▶ Try button. Predict the output first, then run it.
The model: throw unwinds until something catches
throw value stops the current function immediately. JavaScript then unwinds the call stack, function by
function, until it reaches a try block with a catch. If nothing catches it, the error is
uncaught: the browser logs it to the console, and Node prints it and exits the process.
function parseAge(text) {
const age = Number(text);
if (!Number.isInteger(age) || age < 0) throw new RangeError(`Not a valid age: "${text}"`);
return age;
}
function register(form) {
const age = parseAge(form.age); // no try here: the error passes straight through
console.log('registered, age', age);
}
try {
register({ age: '42' });
register({ age: 'forty' });
console.log('never printed');
} catch (err) {
console.log('caught:', err.name, '-', err.message);
}
register didn't need to know about the error at all. That's the point of exceptions: the code that
detects a problem and the code that can handle it are often far apart, and everything in between stays
clean.
You can throw anything (but don't)
throw accepts any value: a string, a number, an object, undefined. The language doesn't stop you,
and some old libraries do it. But only Error objects carry a stack trace, and only they work with
the tools: instanceof Error, err.message, error monitoring, the browser's console.
function check(value) {
try {
throw value;
} catch (err) {
console.log(typeof err, err instanceof Error, err?.message, err?.stack ? 'has a stack' : 'no stack');
}
}
check(new Error('a real error'));
check('just a string');
check({ code: 'E_DISK' });
check(undefined);
Rule: always throw Error objects (or subclasses). The no-throw-literal lint rule enforces it. And
because other code might not follow the rule, never assume that what you catch is an Error.
Built-in error types
The engine throws these for you. Knowing which is which tells you what kind of bug you're looking at:
| Type | Typical cause |
|---|---|
TypeError | Using a value the wrong way: null.x, calling something that isn't a function, assigning to a const |
ReferenceError | A name that doesn't exist, or a let/const used before its declaration |
RangeError | A number out of range: new Array(-1), toFixed(101), and "Maximum call stack size exceeded" |
SyntaxError | Invalid code or data: JSON.parse('{bad'), a bad regex in new RegExp(...) |
URIError | decodeURIComponent('%') |
AggregateError | Several errors at once: Promise.any when everything fails |
const attempts = [
() => null.name,
() => missingVariable,
() => new Array(-1),
() => JSON.parse('{bad json'),
() => decodeURIComponent('%'),
];
for (const attempt of attempts) {
try {
attempt();
} catch (err) {
console.log(err.name);
}
}
The exact message text differs between engines, so never parse it. Branch on the type (or on your own
error properties) instead.
Browsers and Node also throw DOMExceptions, which are Errors too. The one you'll meet most is
AbortError, when an AbortController cancels a fetch, and TimeoutError from AbortSignal.timeout().
Anatomy of an Error
const err = new Error('Config file not found', { cause: 'ENOENT' });
console.log(err.name); // "Error", from the prototype
console.log(err.message);
console.log(err.cause);
console.log(String(err)); // "name: message"
console.log(err.stack.split('\n')[0]); // the first line of the stack trace
console.log(JSON.stringify(err)); // {} !
message: the human-readable description.name: the type name.String(err)is"name: message".stack: the stack trace as a string. It isn't in the language spec, but every engine has it. It's captured when the Error is created, not when it's thrown.cause(ES2022): the error (or any value) that led to this one. Pass it as{ cause }in the second argument.
JSON.stringify(err) gives {}, because message and stack aren't enumerable properties. That trips
up every team that sends errors to a log endpoint as JSON. The Serialize errors for logging exercise
fixes it.
Custom error classes
Subclass Error to add a type you can check with instanceof and data the handler needs:
class HttpError extends Error {
constructor(status, url, options) {
super(`HTTP ${status} for ${url}`, options);
this.name = 'HttpError';
this.status = status;
this.url = url;
}
}
class NotFoundError extends HttpError {
constructor(url, options) {
super(404, url, options);
this.name = 'NotFoundError';
}
}
const err = new NotFoundError('/api/orders/7');
console.log(err instanceof NotFoundError, err instanceof HttpError, err instanceof Error);
console.log(String(err), err.status);
Three details to get right:
- Call
super(message, options)and passoptionsalong, so{ cause }works. - Set
name. Without it,err.nameis the inherited"Error", and logs andString(err)won't show your class. Write the name as a string:this.constructor.namelooks clever, but a minifier renames classes in production builds, and your logs fill up with"t"and"e". - Add data as properties (
status,url,field,code), not by encoding it in the message. Code should branch onerr.status === 404, never onerr.message.includes('404').
TypeScript history note: when TypeScript compiled classes down to ES5, instanceof on Error
subclasses returned false unless you called Object.setPrototypeOf(this, new.target.prototype) in the
constructor. You'll still see that line in older code. With any modern target (ES2015+), it isn't needed.
Wrapping errors with cause
Low-level errors make poor messages: "Unexpected end of JSON input" doesn't tell anyone
which file. High-level messages lose the details. cause keeps both:
function loadSettings(text) {
try {
return JSON.parse(text);
} catch (err) {
throw new Error('Could not read settings.json', { cause: err });
}
}
try {
loadSettings('{ "theme": ');
} catch (err) {
for (let e = err; e; e = e.cause) console.log(`${e.name}: ${e.message}`);
}
Each layer adds what it knows ("which file", "which user", "which order"), and the chain says exactly
what happened. Node's console.log(err) prints the whole cause chain, and error monitoring tools like
Sentry and Datadog show it too.
try, catch, finally: the exact rules
function demo(shouldFail) {
try {
console.log(' try');
if (shouldFail) throw new Error('boom');
return 'from try';
} catch (err) {
console.log(' catch', err.message);
return 'from catch';
} finally {
console.log(' finally'); // runs in every case, AFTER the return value is decided
}
}
console.log(demo(false));
console.log(demo(true));
catchruns only if thetryblock threw.finallyruns always: aftertryfinishes, aftercatchfinishes, and even whentryorcatchexecutesreturn,breakorcontinue. It's the place for cleanup: close the file, release the lock, hide the spinner.- The binding is optional:
catch { ... }when you don't need the error.
finally can override a return, and swallow an error
If finally itself executes return (or throw), that replaces whatever the try or catch was
doing, including an error in flight:
function overrides() {
try {
return 'try';
} finally {
return 'finally'; // wins
}
}
function swallows() {
try {
throw new Error('important failure');
} finally {
return 'everything is fine'; // the error is silently discarded
}
}
let counter = 1;
function decidedEarly() {
try {
return counter; // the value 1 is decided here...
} finally {
counter = 2; // ...so changing the variable afterwards doesn't affect it
}
}
console.log(overrides());
console.log(swallows());
console.log(decidedEarly(), counter);
ESLint's no-unsafe-finally rule flags return, throw, break and continue in finally. C#
doesn't even compile a return inside finally. In JavaScript, treat finally as cleanup-only.
Rethrow what you can't handle
JavaScript has one catch per try and no catch (SomeType e) filter. So the pattern is: check, handle
what you understand, and rethrow everything else.
class NotFoundError extends Error {
constructor(message) {
super(message);
this.name = 'NotFoundError';
}
}
function findUser(id) {
if (id === 1) return { id, name: 'Ana' };
if (id === 2) throw new NotFoundError(`No user ${id}`);
throw new TypeError('database driver crashed');
}
function userNameOrGuest(id) {
try {
return findUser(id).name;
} catch (err) {
if (err instanceof NotFoundError) return 'Guest'; // expected: handle it
throw err; // a bug or an outage: not ours to hide
}
}
console.log(userNameOrGuest(1));
console.log(userNameOrGuest(2));
try {
userNameOrGuest(3);
} catch (err) {
console.log('still visible upstream:', err.message);
}
A catch that logs and continues for every error turns real bugs (a TypeError from a typo) into
silent wrong behaviour. Catch narrowly.
Rethrowing with throw err keeps the original stack trace, because the stack was captured when the
Error was created. (In C#, throw ex; resets the trace and throw; keeps it. JavaScript has no such
trap.)
Narrowing unknown caught values
Since anything can be thrown, a caught value is really of unknown type. TypeScript makes that explicit
(catch (err) gives err: unknown under strict). In JavaScript, write the same checks yourself before
reading properties:
function getErrorMessage(err) {
if (err instanceof Error) return err.message;
if (typeof err === 'string') return err;
if (typeof err === 'object' && err !== null && typeof err.message === 'string') return err.message;
return 'Unknown error';
}
for (const thrown of [new TypeError('bad type'), 'plain text', { message: 'from a fetch wrapper' }, 42, null]) {
try {
throw thrown;
} catch (err) {
console.log(getErrorMessage(err));
}
}
One subtlety: instanceof Error is false for errors created in another realm: an iframe, or a
vm context in Node. A newer Error.isError(value) fixes that, but it's not in Node 22. Duck typing on
message (as above) is the portable fallback.
Errors in callbacks and promises (briefly)
try/catch only catches errors thrown while the try block is running. A callback that runs later
(a timer, an event, an old-style Node callback) runs after the try has already finished:
function readFileLater(name, callback) {
setTimeout(() => callback(new Error(`ENOENT: ${name}`), null), 0); // Node-style: error first
}
try {
readFileLater('a.txt', (err, data) => {
if (err) return console.log('callback got:', err.message); // the only place to handle it
console.log(data);
});
console.log('try block finished');
} catch {
console.log('never runs: the error happens later');
}
async function main() {
try {
await Promise.reject(new Error('request failed')); // await turns a rejection into a throw
} catch (err) {
console.log('async catch:', err.message);
}
}
main();
- Callback APIs pass the error as the first argument. Check it every time.
- Promises reject instead of throwing.
awaitinsidetryturns a rejection back into a catchable throw, but only if you actuallyawaitit. A promise nobody awaits or.catches is an unhandled rejection. - The Promises and async/await topic covers async errors in depth.
AggregateError: several failures at once
Some operations fail in more than one way at once. AggregateError holds a list of errors in its
errors property:
const failures = [Promise.reject(new Error('mirror 1 down')), Promise.reject(new Error('mirror 2 down'))];
Promise.any(failures).catch((err) => {
console.log(err.name, err.errors.map((e) => e.message));
});
const problems = [new RangeError('age must be positive'), new TypeError('email must be a string')];
const validation = new AggregateError(problems, 'Invalid form: 2 problems');
console.log(validation.message, validation.errors.length, validation instanceof Error);
Use it when the caller benefits from all the problems: form validation (show every field's error, not just the first), batch jobs (which of the 500 rows failed?), cleanup that fails in several places.
Results instead of exceptions
Exceptions are for situations the caller can't reasonably plan around. Many failures are expected, though: a user typing an invalid email, a search with no match, a payment declined. For those, returning a result object makes the failure part of the function's contract, and callers can't forget it:
function parsePort(text) {
const port = Number(text);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
return { ok: false, error: `"${text}" is not a port number` };
}
return { ok: true, value: port };
}
for (const input of ['8080', 'http', '70000']) {
const result = parsePort(input);
console.log(result.ok ? `port ${result.value}` : `error: ${result.error}`);
}
| Throw | Return a result |
|---|---|
Bugs and broken invariants (TypeError, a null that "can't happen") | Expected outcomes: invalid input, not found, declined |
| Infrastructure failures the caller can't fix locally | Failures the immediate caller decides about |
| The error should travel up many layers to a central handler | The caller handles it right there, often in UI code |
Real examples: Zod's schema.safeParse(data) returns { success, data } or { success, error }
instead of throwing. React Query returns { data, error, status }. Libraries like neverthrow bring F#
style Result types to TypeScript. The tryCatch exercise builds the bridge between the two styles.
Stack traces
function level3() {
return new Error('where was I made?');
}
function level2() {
return level3();
}
function level1() {
return level2();
}
console.log(level1().stack.split('\n').slice(0, 4).join('\n'));
- The stack lists the functions that were running when the Error was constructed, innermost first. Each line has a file, line and column.
- V8 (Node and Chrome) keeps 10 frames by default (
Error.stackTraceLimit), and showsat async ...frames acrossawaits. - In production, the files are minified bundles, so traces point at
main.4f9c.js:1:58213. Source maps translate them back to your source: upload them to your error monitoring service (Sentry, Datadog) instead of shipping them publicly. Error.captureStackTrace(this, SomeFunction)(a V8 API) hides helper frames from the top of the trace. Libraries use it in their error constructors.
Coming from C#, F# or TypeScript
Side note
- C#: no typed
catch (IOException e)and nowhenfilters: useinstanceofchecks and rethrow (throw err;keeps the stack, unlike C#'sthrow ex;).causeisInnerException,AggregateErrorisAggregateException.finallybehaves the same, except that JavaScript allowsreturninfinally, where it silently wins. Nothing is "checked" in either language. - F#:
Result<'T, 'TError>is the result-object pattern with compiler support. F# separatestry ... withfromtry ... finally; JavaScript combines them in one statement. - TypeScript:
catch (err)isunknownunderstrict(useUnknownInCatchVariables), so you must narrow before readingerr.message. There's nothrowsclause and promise rejections aren't typed, which is one reason teams like result types for expected failures.
In real codebases
Side note
- One central handler per layer. Angular has a global
ErrorHandleryou can replace. React has error boundaries (componentDidCatch, or thereact-error-boundarypackage), which catch errors thrown during rendering, but not in event handlers or async code. Browsers havewindow.onerrorand theunhandledrejectionevent. Node hasprocess.on('uncaughtException')and'unhandledRejection'for logging before exit. - Map errors at boundaries. An API layer turns
fetchresponses intoHttpErrorsubclasses. Express middleware or a serverless function wrapper turns your error classes into status codes (ValidationErrorto 400,NotFoundErrorto 404, anything else to 500, with the details logged but not shown to the user). - Log the chain, show a message. Users get a short, friendly message. Logs get the name, message,
stack,
causechain and context (user id, request id). - Retry only what's transient. Timeouts, 429 and 503 can be retried. A 400 or a
TypeErrorwill fail the same way again. Error classes make that decision a one-lineinstanceof.
The exercises
- getErrorMessage and toError (easy): turn any caught value into a message, or into a real Error.
- Custom error classes (easy):
ValidationErrorandNotFoundErrorwith names, data and causes. - An HTTP error hierarchy (medium): classes per status range, a factory, and walking
causechains. - tryCatch: results instead of exceptions (medium): wrap sync and async code into
{ ok, value }or{ ok, error }. - Collect every validation error (medium): validate a whole form and throw one
AggregateError. - Serialize errors for logging (medium): make errors JSON-safe, with causes and extra fields.
- Retry only what's retryable (hard): classify errors, rethrow the rest, and aggregate failures.
- Cleanup that always runs (hard):
finallyfor several resources, in reverse order, without losing errors.
Practise this lesson
In the app: a short video, 8 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app