Publicado · en mejora
Guía de TypeScript · 5/6
Por ahora, este capítulo solo está disponible en inglés.
Error handling in TypeScript uses the same throw and try...catch you know from JavaScript. The type system makes it safer, though, and it opens up an alternative: describing failure in the return type itself. This chapter covers unknown catch variables, custom error classes, and the result pattern, and then shows how to write tests with Vitest and with the test runner built into Node.js.
JavaScript lets you throw anything, not just Error objects; throw "oops" is perfectly legal. To reflect that, strict mode types the catch variable as unknown (via the useUnknownInCatchVariables option). You have to establish what it is before touching its properties.
function parseConfig(text: string): Record<string, unknown> {
try {
return JSON.parse(text);
} catch (err) {
// err: unknown
if (err instanceof SyntaxError) {
console.error("Malformed JSON:", err.message);
} else {
console.error("Unexpected failure:", err);
}
return {};
} finally {
console.log("Finished reading config");
}
}
function errorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}A tiny helper like errorMessage saves you from repeating the same check in every log statement. In async functions, placing the await inside the try block catches rejected promises the same way.
Subclassing Error lets you tell failures apart by class and attach extra data as properties. Setting name makes the error type stand out in logs, and the cause option links a new error to the one that triggered it.
class NotFoundError extends Error {
constructor(
public readonly resource: string,
options?: ErrorOptions,
) {
super(`Not found: ${resource}`, options);
this.name = "NotFoundError";
}
}
async function loadUser(id: string): Promise<{ id: string; name: string }> {
try {
const res = await fetch(`https://api.example.com/users/${id}`);
if (res.status === 404) throw new NotFoundError(`user ${id}`);
return await res.json();
} catch (err) {
if (err instanceof NotFoundError) throw err;
throw new Error("Could not load user", { cause: err });
}
}For instanceof to recognize subclasses reliably, compile with a target of ES2015 or later. ErrorOptions and cause come from the ES2022 library typings, so set target or lib accordingly.
Exceptions are invisible in a function's signature: nothing in the types tells a caller what might be thrown. For failures that are an expected part of normal operation, such as validating user input, you can return a value that represents either success or failure.
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
function parseAge(input: string): Result<number, string> {
const age = Number(input);
if (!Number.isInteger(age) || age < 0) {
return { ok: false, error: `Not a valid age: ${input}` };
}
return { ok: true, value: age };
}
const result = parseAge("42");
if (result.ok) {
console.log(result.value + 1); // value is available here
} else {
console.error(result.error); // and error is available here
}Because the ok flag separates the two cases, the compiler refuses any attempt to read value before checking for failure. A sensible split is to throw for genuine bugs and unexpected conditions, and to return results for failures the caller is expected to handle.
Vitest runs TypeScript test files with zero configuration. Start with something to test:
// src/math.ts
export function divide(a: number, b: number): number {
if (b === 0) throw new RangeError("Cannot divide by zero");
return a / b;
}// src/math.test.ts
import { describe, it, expect } from "vitest";
import { divide } from "./math.js";
describe("divide", () => {
it("returns the quotient", () => {
expect(divide(10, 4)).toBe(2.5);
});
it("throws a RangeError on division by zero", () => {
expect(() => divide(1, 0)).toThrow(RangeError);
});
it("works with async assertions too", async () => {
await expect(Promise.resolve(divide(9, 3))).resolves.toBe(3);
});
});npm install --save-dev vitest
npx vitest # watch mode, reruns on change
npx vitest run # single run, for CILike most fast tooling, Vitest strips types without checking them. Run tsc --noEmit as a separate step.
If you would rather avoid another dependency, Node.js ships node:test and node:assert. Load tsx as a module hook so Node can execute the .ts files.
// src/math.node.test.ts
import { test } from "node:test";
import assert from "node:assert/strict";
import { divide } from "./math.js";
test("divide computes the quotient", () => {
assert.equal(divide(10, 4), 2.5);
});
test("divide rejects a zero divisor", () => {
assert.throws(() => divide(1, 0), RangeError);
});node --import tsx --test src/math.node.test.tsunknown; narrow them with checks such as instanceof Error first.Error to distinguish failure kinds, and record context with name and cause.{ ok: true } and { ok: false } variants.node:test needs no extra dependency at all.tsc --noEmit in the pipeline.
0 comentarios
Iniciar sesión · Inicia sesión para dejar un comentario.
Sé el primero en comentar.