Type-safe error handling in TypeScript: unknown catch variables, Error subclasses with cause, Result unions for expected failures, literal error codes and exhaustive handling.
.cursor/rules/typescript-error-handling-types.mdc. Downloaded files need to be placed in that repository path.---
description: "Type-safe error handling in TypeScript: unknown catch variables, Error subclasses with cause, Result unions for expected failures, literal error codes and exhaustive handling."
globs: "**/*"
alwaysApply: false
---
Apply these rules to error handling in TypeScript.
## Catch clauses
- With `strict` (or `useUnknownInCatchVariables`), the catch variable is `unknown`. Narrow it before use; never annotate it as `any`.
```ts
function errorMessage(err: unknown): string {
if (err instanceof Error) return err.message;
if (typeof err === 'string') return err;
return 'Unknown error';
}
```
## Exceptions for unexpected failures
- Throw `Error` subclasses for bugs and infrastructure failures, set `name`, and keep the original error as `cause` when wrapping:
```ts
export class DatabaseError extends Error {
override name = 'DatabaseError';
constructor(message: string, options?: { cause?: unknown }) {
super(message, options);
}
}
```
- Keep the hierarchy shallow (a base `AppError` and a few subclasses); check with `instanceof`.
## Result types for expected failures
- For failures callers must handle (validation, not found, conflict), return a discriminated union instead of throwing, so the compiler forces the caller to check:
```ts
export type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
export type CreateUserError =
| { code: 'EMAIL_TAKEN'; email: string }
| { code: 'INVALID_EMAIL'; email: string }
| { code: 'RATE_LIMITED'; retryAfterSeconds: number };
export function describe(error: CreateUserError): string {
switch (error.code) {
case 'EMAIL_TAKEN':
return `${error.email} is already registered`;
case 'INVALID_EMAIL':
return `${error.email} is not a valid email`;
case 'RATE_LIMITED':
return `Try again in ${error.retryAfterSeconds}s`;
default: {
const unhandled: never = error;
return unhandled;
}
}
}
```
- Use string-literal unions for error codes; they are already distinct types, so branding is not needed.
- The `never` default makes adding a new error variant a compile error at every unhandled switch.
## Documentation
- Document thrown errors with `@throws` in JSDoc and the error union in the return type for Result-returning functions.
## Avoid
- `any` in error paths (`catch (e: any)`, `as any`), throwing strings or plain objects, and swallowing errors with an empty `catch`.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
language
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A signup service throws strings for validation failures and the UI catches with `catch (e: any) { alert(e.message) }`, so some errors show 'undefined'.
Using the TypeScript Error Handling Types rule, refactor src/services/signup.ts and its caller SignupForm.tsx.
createUser returns Result<User, CreateUserError> with code-literal variants; unexpected failures are Error subclasses with cause; the caller switches on error.code with a never-typed default; catch blocks use unknown with an errorMessage helper.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/typescript-error-handling-types.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "TypeScript Error Handling Types project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these rules to error handling in TypeScript.
## Catch clauses
- With `strict` (or `useUnknownInCatchVariables`), the catch variable is `unknown`. Narrow it before use; never annotate it as `any`.
```ts
function errorMessage(err: unknown): string {
if (err instanceof Error) return err.message;
if (typeof err === 'string') return err;
return 'Unknown error';
}
```
## Exceptions for unexpected failures
- Throw `Error` subclasses for bugs and infrastructure failures, set `name`, and keep the original error as `cause` when wrapping:
```ts
export class DatabaseError extends Error {
override name = 'DatabaseError';
constructor(message: string, options?: { cause?: unknown }) {
super(message, options);
}
}
```
- Keep the hierarchy shallow (a base `AppError` and a few subclasses); check with `instanceof`.
## Result types for expected failures
- For failures callers must handle (validation, not found, conflict), return a discriminated union instead of throwing, so the compiler forces the caller to check:
```ts
export type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
export type CreateUserError =
| { code: 'EMAIL_TAKEN'; email: string }
| { code: 'INVALID_EMAIL'; email: string }
| { code: 'RATE_LIMITED'; retryAfterSeconds: number };
export function describe(error: CreateUserError): string {
switch (error.code) {
case 'EMAIL_TAKEN':
return `${error.email} is already registered`;
case 'INVALID_EMAIL':
return `${error.email} is not a valid email`;
case 'RATE_LIMITED':
return `Try again in ${error.retryAfterSeconds}s`;
default: {
const unhandled: never = error;
return unhandled;
}
}
}
```
- Use string-literal unions for error codes; they are already distinct types, so branding is not needed.
- The `never` default makes adding a new error variant a compile error at every unhandled switch.
## Documentation
- Document thrown errors with `@throws` in JSDoc and the error union in the return type for Result-returning functions.
## Avoid
- `any` in error paths (`catch (e: any)`, `as any`), throwing strings or plain objects, and swallowing errors with an empty `catch`.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.