TypeScript is good at telling you what a function returns. It is much quieter about what a function might throw. A call can fail in a dozen ways, and none of them show up in its signature. Then, when you catch the failure, the compiler hands you a value of type unknown and leaves you to work out what it is.
This article is for developers who write TypeScript every day and want a clear, consistent way to deal with errors. We will start with why catch gives you unknown, move on to narrowing and custom error classes, chain errors together with Error.cause, and finish with Result types for failures you expect to happen.
Why catch gives you unknown
#In JavaScript you can throw anything. A string, a number, null, a plain object or a real Error are all valid.
_10throw "something went wrong";_10throw { code: 42 };_10throw new Error("something went wrong");
Because of this, TypeScript cannot know what lands in a catch clause. For years it typed the variable as any, which meant you could write err.message and the compiler would happily let you, even if err was a string.
TypeScript 4.4 added the useUnknownInCatchVariables option, and it is switched on by strict. With it, the catch variable is unknown.
_10try {_10 JSON.parse(input);_10} catch (err) {_10 console.log(err.message);_10 // Error: 'err' is of type 'unknown'._10}
This feels annoying at first, but it is honest. The compiler is telling you that you have not checked yet. Leave the option on, and learn the few patterns that make unknown easy to work with.
Narrowing what you caught
#The most common check is instanceof Error.
_10try {_10 JSON.parse(input);_10} catch (err) {_10 if (err instanceof Error) {_10 console.error(err.message);_10 } else {_10 console.error("Unknown error", err);_10 }_10}
This works well in most code. It has one weak spot: an error created in a different realm, such as an iframe or a Node vm context, has a different Error constructor, so instanceof returns false.
The newer Error.isError() method fixes that. It checks whether a value is a genuine error object, whatever realm it came from. It is part of ECMAScript 2026 and works in current Chrome, Edge and Firefox, but Safari support is still only partial and it is not Baseline yet. For now, treat it as a nice extra rather than something to depend on in browser code.
In practice, a small helper that turns any thrown value into an Error covers most needs.
_16export function toError(value: unknown): Error {_16 if (value instanceof Error) return value;_16 if (typeof value === "string") return new Error(value);_16 try {_16 return new Error(JSON.stringify(value));_16 } catch {_16 return new Error(String(value));_16 }_16}_16_16try {_16 await saveDraft(draft);_16} catch (err) {_16 const error = toError(err);_16 logger.error(error.message, { stack: error.stack });_16}
Notice the bare catch with no variable in the helper. Optional catch binding has been part of JavaScript since ES2019, and it is the clearest way to say you do not care what was thrown.
Custom error classes
#When callers need to react differently to different failures, a custom class gives them something solid to check.
_19export class NotFoundError extends Error {_19 readonly resource: string;_19_19 constructor(resource: string, options?: ErrorOptions) {_19 super(`${resource} was not found`, options);_19 this.name = "NotFoundError";_19 this.resource = resource;_19 }_19}_19_19export class ValidationError extends Error {_19 readonly field: string;_19_19 constructor(field: string, message: string, options?: ErrorOptions) {_19 super(message, options);_19 this.name = "ValidationError";_19 this.field = field;_19 }_19}
A few details matter here:
- Set
name****. Stack traces and many logging tools print it. Without it, every error saysError. - Accept
ErrorOptionsand pass it tosuper****. This is what lets callers attach a cause, which we cover next. - Declare fields explicitly. Parameter properties such as
constructor(readonly field: string)are not allowed undererasableSyntaxOnly, so plain field declarations keep the class compatible with Node's type stripping.
You may have seen advice to call Object.setPrototypeOf(this, new.target.prototype) in error subclasses. That was only needed when compiling to ES5. With any modern target, instanceof NotFoundError works without it.
Now the caller can branch on the type:
_10try {_10 const post = await getPost(slug);_10 return render(post);_10} catch (err) {_10 if (err instanceof NotFoundError) {_10 return renderNotFound();_10 }_10 throw err;_10}
The last line is important. If you catch something you do not know how to handle, throw it again. Swallowing unknown errors is how bugs hide for months.
Chaining errors with Error.cause
#Low-level errors are often too vague to be useful on their own. ECONNREFUSED tells you a connection failed, but not which part of your app was trying to do what. The usual fix used to be building a new message and losing the original stack.
Error.cause, added in ES2022, lets you wrap an error and keep the original attached.
_11async function loadUser(id: string) {_11 try {_11 const res = await fetch(`https://api.example.com/users/${id}`);_11 if (!res.ok) {_11 throw new Error(`Request failed with ${res.status}`);_11 }_11 return await res.json();_11 } catch (err) {_11 throw new Error(`Could not load user ${id}`, { cause: err });_11 }_11}
The new error describes the failure in terms of your app. The original is still there on error.cause. Node prints the whole chain when an error is logged or goes uncaught, and browser devtools show it too, so you get both the high-level story and the root stack trace.
To use the second argument in TypeScript, your lib setting needs to include es2022 or later. Any target of es2022 or higher includes it by default.
The type of cause is unknown, for the same reason the catch variable is. When you walk the chain, narrow as you go.
_13function describe(error: unknown): string[] {_13 const lines: string[] = [];_13 let current: unknown = error;_13_13 while (current instanceof Error) {_13 lines.push(`${current.name}: ${current.message}`);_13 current = current.cause;_13 }_13_13 return lines;_13}_13_13// ["Error: Could not load user 7", "TypeError: fetch failed", "Error: connect ECONNREFUSED ..."]
A good rule: wrap an error when you cross a boundary where the meaning changes, such as from "the network failed" to "we could not load the user". Do not wrap at every function call, or your logs fill up with five layers saying the same thing.
Result types for expected failures
#Exceptions are a good fit for things that should not happen: bugs, broken invariants, a database that has vanished. They are a poor fit for failures you fully expect, such as a form field that fails validation or a user that does not exist. In those cases the failure is a normal outcome, and hiding it in an invisible throw makes it easy to forget.
A Result type makes the failure part of the return value, so the compiler forces callers to deal with it. You do not need a library. A discriminated union is enough.
_10export type Result<T, E = Error> =_10 | { ok: true; value: T }_10 | { ok: false; error: E };_10_10export const ok = <T>(value: T): Result<T, never> => ({ ok: true, value });_10export const err = <E>(error: E): Result<never, E> => ({ ok: false, error });
Here is a function that parses a port number from configuration:
_14type PortError =_14 | { kind: "missing" }_14 | { kind: "not-a-number"; raw: string }_14 | { kind: "out-of-range"; port: number };_14_14function parsePort(raw: string | undefined): Result<number, PortError> {_14 if (raw === undefined) return err({ kind: "missing" });_14_14 const port = Number(raw);_14 if (!Number.isInteger(port)) return err({ kind: "not-a-number", raw });_14 if (port < 1 || port > 65535) return err({ kind: "out-of-range", port });_14_14 return ok(port);_14}
The caller has to check ok before it can touch value:
_18const result = parsePort(process.env.PORT);_18_18if (!result.ok) {_18 switch (result.error.kind) {_18 case "missing":_18 console.error("PORT is not set");_18 break;_18 case "not-a-number":_18 console.error(`PORT must be a number, got "${result.error.raw}"`);_18 break;_18 case "out-of-range":_18 console.error(`PORT ${result.error.port} is out of range`);_18 break;_18 }_18 process.exit(1);_18}_18_18startServer(result.value); // result.value is number here
Two things are worth pointing out. First, the error type is a union of plain objects rather than classes. That keeps it serialisable and lets switch narrow each case. Second, if you add a new kind of PortError, you can make the compiler flag every switch that does not handle it by adding a default branch that assigns result.error to a variable of type never.
Wrapping code that throws
#Most of the libraries you use will still throw. A small helper turns a promise that may reject into a Result, so you can keep the rest of your code consistent.
_15export async function attempt<T>(promise: Promise<T>): Promise<Result<T>> {_15 try {_15 return ok(await promise);_15 } catch (e) {_15 return err(toError(e));_15 }_15}_15_15const result = await attempt(fetch("https://api.example.com/health"));_15_15if (!result.ok) {_15 console.error("Health check failed", result.error);_15} else {_15 console.log("Status", result.value.status);_15}
This is where toError from earlier pays off. Whatever the library threw, the Result always holds a real Error.
Putting it together
#In a real codebase you will use all three tools, each in its place:
- Throw for bugs and for failures nobody near the call can handle. Let them travel up to a top-level handler, an error boundary or a framework error page.
- Wrap with
causewhen an error crosses a layer and needs a clearer message, without losing the original. - Return a Result for expected outcomes the immediate caller must handle, such as validation, parsing and "not found" lookups.
The edges of your app are where these meet. A route handler might call a service that returns a Result, turn an ok: false into a 400 response, and let anything thrown fall through to the framework's 500 handling.
_11export async function POST(request: Request) {_11 const body = await request.json().catch(() => null);_11 const result = validateSignup(body);_11_11 if (!result.ok) {_11 return Response.json({ errors: result.error }, { status: 400 });_11 }_11_11 await createAccount(result.value); // throws only if something is truly broken_11 return Response.json({ ok: true }, { status: 201 });_11}
Version support
#unknownin catch clauses arrived in TypeScript 4.4 and is on wheneverstrictis on, including in TypeScript 6.Error.causeand theErrorOptionsargument are ES2022. They work in every current browser and in all supported Node versions. TypeScript needslibto includees2022or later.Error.isError()is ES2026. It works in current Chrome, Edge and Firefox, but Safari support is partial, so check before relying on it in browser code.- Discriminated unions and the Result pattern are plain types. They work in any TypeScript version and have no runtime cost beyond the small objects you create.
When not to use it
#Result types are useful, but they are not free. Skip them when:
- Nobody nearby can handle the failure. Passing a Result up through six layers that just return it again is worse than a throw that travels on its own.
- The failure is a bug. A missing environment variable at startup, or an impossible state in a reducer, should crash loudly. Returning it as data invites someone to ignore it.
- You are working with a framework that expects throws. Next.js
notFound()andredirect(), React error boundaries and many test runners all rely on thrown values. Fighting that convention adds friction for little gain. - The team has not agreed on it. A codebase where half the functions throw and half return Results, with no clear rule, is harder to read than one that only throws.
And avoid wrapping with cause at every level. One or two meaningful layers is plenty.
Wrapping up
#- Keep
useUnknownInCatchVariableson. Narrow withinstanceof Erroror atoErrorhelper rather than casting. - Custom error classes should set
name, acceptErrorOptionsand pass them tosuper. - Use
Error.causeto add context when an error crosses a boundary, and keep the original stack. - Reach for a Result type when a failure is an expected outcome the caller must handle.
- Rethrow anything you catch but do not understand.
Test yourself
Testing yourself is one of the best ways to make what you read stick. Turn over each card and answer the 5 questions to see how much you remember.
quick question
Was this article helpful?
by Danny