---
name: handling-typescript-errors
description: Handle errors in TypeScript without losing their cause - Error objects, unknown catch values, { cause }, no empty catch blocks, result unions for expected outcomes, and clean CLI exits. Use when writing or reviewing try/catch, throw, or error types in TypeScript.
license: MIT
compatibility: Requires TypeScript with ES2022 lib or later, for Error cause.
metadata:
author: famiglio
category: code
---
# Handling TypeScript Errors
Handle errors so the message says what failed, and the cause says why.
## Procedure
1. **Throw `Error` objects**, or subclasses, never strings or plain objects. Only `Error` has a stack.
2. **Narrow the caught value**, which is `unknown`:
```ts
import { readFile } from 'node:fs/promises';
export async function readOptional(
path: string,
): Promise<string | undefined> {
try {
return await readFile(path, 'utf8');
} catch (error) {
// A missing file is fine: the caller uses the defaults.
if (
error instanceof Error &&
'code' in error &&
error.code === 'ENOENT'
) {
return undefined;
}
throw new Error(`Could not read ${path}`, { cause: error });
}
}
<!-- ‹guest · 2026-12-05› -->
```
- The expected error is handled, with the reason in a comment.
- Every other error is rethrown, with the original as `cause`.
3. **Never write an empty `catch`.** If an error can be ignored, say why, and ignore only that error.
4. **Return a union for outcomes the caller must handle:**
```ts
type FindUser =
{ ok: true; user: User } | { ok: false; reason: 'not-found' };
```
Throw for bugs and for failures of the infrastructure, such as a lost connection.
5. **In a CLI, end cleanly:**
```ts
main().catch((error: unknown) => {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
});
```
`process.exitCode` lets pending output finish. `process.exit(1)` can cut it.
## Verification
```bash
git grep -nE 'catch[[:space:]]*(\([^)]*\))?[[:space:]]*\{[[:space:]]*\}' -- '*.ts' '*.tsx' '*.mts' '*.cts' || echo "No empty catch."
git grep -nE "throw[[:space:]]+['\"\`]" -- '*.ts' '*.tsx' '*.mts' '*.cts' || echo "No thrown strings."
```
Then run the project's type check.
این نسخه با نشانهگذاری اختصاصی حساب شما نمایش داده میشود. برای نصب سریع، به تب نصب و راهاندازی بروید.