Recognize results and ignored values
#Thrown failures use try/catch; await makes a rejected Promise throw here. Numeric conversion often returns NaN instead of throwing. void discards a value.
Fragment
Fragment inside a function.
Reference
Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.
TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.
TypeScript docs MDN try...catch ↗MDN Error ↗
Thrown failures use try/catch; await makes a rejected Promise throw here. Numeric conversion often returns NaN instead of throwing. void discards a value.
Fragment
Fragment inside a function.
throw exits until caught. With strict checking, a caught value is unknown and need not be an Error. An awaited rejected Promise throws at the await point. A type annotation does not make exceptions part of the return type.
Fragment
Fragment: imports and type/function declarations at file scope; usage statements inside a function.
finally runs when leaving a try through ordinary completion, return or a thrown exception. Use it for the cleanup the API requires. Garbage collection does not guarantee timely release of external resources.
Fragment
Fragment: imports and type/function declarations at file scope; usage statements inside a function.
TypeScript inherits JavaScript's model: failures are thrown and caught with try/catch, and a rejected promise throws at the await. Exceptions are invisible in function types, so nothing tells a caller which calls can fail or with what; catch receives unknown. The alternatives are conventions you build yourself: return a discriminated union such as { ok: true, value } | { ok: false, error }, return undefined or null for "not found", or use a library Result type. There are no error codes beyond fields you add (Node.js system errors carry code: 'ENOENT' and so on), and no separate panic mechanism: a bug is an exception nobody catches.
Complete program
Complete program.
Trade-offs: exceptions cost nothing to write and propagate automatically, but are easy to forget and hard to type. Result unions show failure in the signature and force a check, at the price of explicit plumbing at every call.
In practice: throw for unexpected or environmental failures (I/O, broken invariants); return a union for expected, domain-level outcomes the caller must decide on (validation, "already exists"); return undefined for plain absence. Catch narrowly, check with instanceof, and rethrow what you do not handle.
A function that returns a Result union can still throw: JSON.parse, property access on undefined and library calls inside it all throw normally. Results narrow what callers must check; they do not remove exceptions.
Any value can be thrown, not only Error instances. Throw Error (or a subclass) so there is a stack trace and a message.
neverthrow 8.2.0 and Effect 4.1.2 are popular libraries that add typed Result and effect types; the union shown here needs no dependency.
A custom error is a class that extends Error. Add fields the caller can branch on: a stable code string, the field or resource involved. Set name so stack traces and String(error) show the subclass, and pass { cause } through to super so the original failure is kept. Callers narrow the unknown value in catch with instanceof, which then types the extra fields.
Complete program
Complete program.
In practice: keep a small hierarchy (one base class with a code, a few subclasses for outcomes callers treat differently). Branch on instanceof or code, never on message text. If errors cross a process or network boundary, instanceof no longer works; serialize the code and check that instead.
instanceof fails across realms (iframes, vm contexts) and between two copies of the same package in node_modules. A code field survives both, and Error.isError(value) (ES2026, Node.js 24+) tells whether a value is a genuine Error from any realm.
ErrorOptions and cause need lib es2022 or later in tsconfig. With older compile targets (ES5), subclassing Error breaks instanceof unless you call Object.setPrototypeOf(this, new.target.prototype).
Parameter properties (constructor(readonly code: string)) are not erasable syntax, so Node.js type stripping and the erasableSyntaxOnly option reject them; declare the fields explicitly as shown.
new Error(message, { cause }) (ES2022) creates a new error that says what this layer was doing and keeps the original as error.cause. Catch, wrap, and rethrow at each layer that has useful context to add; the result is a chain you can walk to print or inspect. cause is typed unknown, because anything can be thrown, so check instanceof Error before reading it.
Complete program
Complete program.
In practice: wrap where you know something the low-level error does not (which file, which user, which step), and keep messages short; the chain supplies the rest. Search the chain for a code (ENOENT) or a known subclass rather than parsing the outer message. Node.js and browsers print causes in uncaught error output.
cause is only set when the options object has a cause property; new Error(msg, { cause: undefined }) sets it to undefined explicitly, which still shows up as an own property.
Do not wrap and also log at every layer; wrap on the way up and log once where the error is finally handled.
A cause may come from another realm (a vm context, a worker message) where instanceof Error is false. Error.isError(value) (ES2026, Node.js 24+) recognizes those too.
TypeScript has no built-in Result, but discriminated unions make one in two lines: { ok: true; value: T } | { ok: false; error: E }. Checking r.ok narrows to the right branch, so value cannot be read without the check. Make the error a union too, with a kind tag and per-kind data; a switch on kind with a never assignment in the default fails to compile when someone adds a kind and forgets to handle it. Small helpers (ok, err, andThen) keep the plumbing short.
Complete program
Complete program.
In practice: use Result unions for expected, domain-level failures the caller must handle (validation, "not found", "reserved name"), and keep throwing for bugs and environmental failures. Keep error kinds as plain data so they serialize, log and test easily.
Wrapping every function in a Result spreads plumbing through the codebase. Draw the line at module boundaries and expected outcomes.
neverthrow 8.2.0 provides Result and ResultAsync classes with map, andThen and match; Effect 4.1.2 goes further with typed errors in its Effect type. Both are dependencies; the union here is not.
If the error union is ever widened to string, the never check stops helping. Keep kind a union of literals.
JavaScript has no separate panic mechanism. An exception that nobody catches, or a rejected promise nobody handles, ends the Node.js process with exit code 1 and a stack trace (unhandled rejections do so by default since Node.js 15). node:assert throws AssertionError, which is just another uncaught exception. process.on('uncaughtException') can log a fatal error, but the process is in an unknown state at that point and should exit.
Complete program
Complete program.
When to crash: when an invariant is broken (a bug), when startup configuration is missing, or when state may be corrupt. Do not catch everything to keep a process alive; let it exit and have a supervisor (systemd, Kubernetes, a process manager) restart it. In a server, catch per request at the framework boundary so one bad request becomes a 500, not a crash.
Resuming normal work after uncaughtException is unsafe: half-finished operations, open transactions and locks are left as they were. Log, flush and exit.
In browsers an uncaught error does not stop the page; it fires the error or unhandledrejection event on window and the next event handler still runs.
process.exitCode = 1 sets the status but lets pending work finish; process.exit(1) stops immediately and can drop buffered output written to a pipe.
AggregateError (ES2021) wraps several errors in one: new AggregateError(errors, message), with the list on error.errors. Promise.any rejects with one when every promise fails. For concurrent work, Promise.allSettled waits for every promise and returns { status: 'fulfilled', value } or { status: 'rejected', reason } for each, so you can keep the successes and gather the failures; Promise.all instead rejects on the first failure.
Complete program
Complete program.
In practice: for form or config validation, check every field and report all problems together, either as an AggregateError or as a returned array of field errors (often easier for a UI). For batches, use allSettled and decide afterwards whether partial success is acceptable.
AggregateError.errors is typed any[]; check each entry with instanceof before reading fields.
Promise.allSettled does not cancel the remaining work when one fails, and an unbounded list starts every task at once. Limit concurrency for large batches.
Most code should let errors pass through. Handle an error only where you can do something about it: retry, fall back, translate it, or turn it into a response. Three boundaries matter. At a module boundary (storage, an HTTP client), translate low-level errors (driver codes, socket errors) into domain errors the rest of the program understands, keeping the original as cause. At the top (a request handler, a CLI main), decide the status code and the user-facing message, and log once with a request id. Retries belong next to the call that failed, and only for transient errors.
Complete program
Complete program.
In practice: never show internal messages (SQL, hostnames, stack traces) to users; give them a short message and a reference id, and put the details in the log. Do not log and rethrow at every layer, which produces the same failure many times. Retry with a limit, capped exponential backoff with jitter and a deadline (an AbortSignal), and never retry validation or "already exists" errors.
Full jitter (a random wait between 0 and the current ceiling) stops many clients that failed together from retrying together. The setTimeout from node:timers/promises rejects with an AbortError when the signal fires, which ends the retries.
Only retry operations that are safe to repeat (idempotent), or the retry may apply a write twice.
Expected outcomes such as 409 Conflict are not errors from the service's point of view; logging them as errors floods alerts.