TypeScript · Lesson 37 of 42
Handling errors safely with unknown
Catch errors safely, understand why the catch variable is unknown, narrow it with instanceof, write custom error classes, and attach a cause.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will handle failures without trusting what was thrown, build your own error types, and decide when an error should be thrown and when it should simply be returned. Error handling is where optimistic code meets reality, and TypeScript's strictness here saves real bugs.
Anything can be thrown
In JavaScript, you can throw any value, not only error objects:
function risky(kind: number): void {
if (kind === 1) throw new Error("an Error object");
if (kind === 2) throw "a plain string";
throw 404;
}
for (const kind of [1, 2, 3]) {
try {
risky(kind);
} catch (e) {
console.log(typeof e, e instanceof Error);
}
}object true
string false
number falseBecause anything may arrive in a catch clause, TypeScript types the variable as unknown when strict is on (the option behind this is useUnknownInCatchVariables). You cannot use it until you check what it is:
try {
JSON.parse("{ not valid");
} catch (e) {
console.log(e.message);
}example.ts(4,15): error TS18046: 'e' is of type 'unknown'.Narrowing the caught value
The standard fix is an instanceof Error check, which narrows unknown to Error:
try {
JSON.parse("{ not valid");
} catch (e) {
if (e instanceof Error) {
console.log("Error:", e.name);
} else {
console.log("Something else was thrown:", e);
}
}Error: SyntaxErrorWriting that everywhere gets repetitive, so many projects keep one small helper that turns anything into a message:
function toMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
if (typeof error === "string") {
return error;
}
return "Unknown error";
}
try {
throw "disk full";
} catch (e) {
console.log(toMessage(e));
}disk fullCustom error classes
Subclassing Error lets you create failures that callers can tell apart, and attach extra data:
class ValidationError extends Error {
constructor(
message: string,
public field: string,
) {
super(message);
this.name = "ValidationError";
}
}
class NotFoundError extends Error {
constructor(public resource: string) {
super(`${resource} not found`);
this.name = "NotFoundError";
}
}
function load(id: number): string {
if (id < 0) throw new ValidationError("id must be positive", "id");
if (id > 100) throw new NotFoundError("user");
return "user " + id;
}
for (const id of [5, -1, 500]) {
try {
console.log(load(id));
} catch (e) {
if (e instanceof ValidationError) {
console.log(`Invalid ${e.field}: ${e.message}`);
} else if (e instanceof NotFoundError) {
console.log(`Missing ${e.resource}`);
} else {
throw e;
}
}
}user 5
Invalid id: id must be positive
Missing userEach instanceof check narrows to a specific class, so e.field and e.resource are available. The final else { throw e; } is an important habit: if you do not know how to handle a failure, rethrow it rather than swallowing it.
Adding a cause
When you catch an error and throw a new one, keep the original with the cause option, so the chain of causes is not lost:
function readConfig(text: string): unknown {
try {
return JSON.parse(text);
} catch (error) {
throw new Error("Could not read the configuration", { cause: error });
}
}
try {
readConfig("{ broken");
} catch (e) {
if (e instanceof Error) {
console.log(e.message);
console.log(e.cause instanceof Error ? "cause: " + e.cause.name : "no cause");
}
}Could not read the configuration
cause: SyntaxErrorThe cause option is available in modern JavaScript, and the compiler needs a lib of ES2022 or later to know about it.
Throw or return?
Not every failure deserves an exception. A useful split:
- Throw for unexpected problems that the caller cannot sensibly continue from, such as a corrupted file or a programming mistake.
- Return a result for expected failures, such as validation of user input or "user not found", where the caller is meant to handle both outcomes.
For the second kind, the discriminated union pattern from the earlier lesson makes the failure part of the type, so the compiler forces callers to handle it:
type Result<T> =
| { ok: true; value: T }
| { ok: false; error: string };
function parsePort(input: string): Result<number> {
const port = Number(input);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
return { ok: false, error: `"${input}" is not a valid port` };
}
return { ok: true, value: port };
}
for (const text of ["8080", "http", "99999"]) {
const result = parsePort(text);
console.log(result.ok ? `port ${result.value}` : result.error);
}port 8080
"http" is not a valid port
"99999" is not a valid portfinally
A finally block runs whether or not an error occurred, which is the right place to release resources such as open files or connections:
function work(shouldFail: boolean): void {
try {
console.log("start");
if (shouldFail) throw new Error("boom");
console.log("done");
} catch {
console.log("recovered");
} finally {
console.log("cleanup");
}
}
work(false);
work(true);start
done
cleanup
start
recovered
cleanupNotice catch without a variable, which is allowed when you do not need the error.
Common mistakes
Assuming the caught value is an Error. It may be anything. Narrow it first.
Swallowing errors. An empty catch hides bugs. Handle it, log it or rethrow it.
Throwing strings. Throw Error objects, because they carry a stack trace.
Forgetting to keep the original error. Use cause when wrapping.
Using exceptions for normal outcomes. "Not found" in a search is not exceptional. Return a result.
Exercise
Write a parseJson(text: string): Result<unknown> that never throws. Write a custom HttpError class with a status property and a function that throws it for status codes 400 and above. Catch it, narrow it with instanceof, and print the status. Finally, write toMessage and test it with an Error, a string and null.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.