Cursor rule for Node.js async error handling with no floating promises, error cause chains, AbortSignal timeouts, a crash-on-uncaught policy and rejection tests.
.cursor/rules/nodejs-async-error-handling.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for Node.js async error handling with no floating promises, error cause chains, AbortSignal timeouts, a crash-on-uncaught policy and rejection tests."
globs: "**/*"
alwaysApply: false
---
# Node.js Async Error Handling
Applies to: promises, `async`/`await`, timeouts and process-level error handling in Node.js services and scripts.
Version baseline: checked against the Node.js 24 documentation. Read `package.json` (`engines`, `type`) first. `AbortSignal.timeout()` needs Node.js 16.14+ and `AbortSignal.any()` needs 18.17+ (or 20.3+ on the 20 line); on older runtimes fall back to an `AbortController` with `setTimeout`.
## Rules
1. **Every promise is awaited, returned or explicitly handled.** A floating promise loses its error. If fire-and-forget is intended, attach `.catch()` that logs, and say why in a comment. Enable `@typescript-eslint/no-floating-promises` or an equivalent lint rule when the project uses TypeScript.
2. **Catch only where you can act.** Wrap with `try`/`catch` when you can retry, fall back, translate the error into a domain error or HTTP status, or add context. Otherwise let it propagate to the central handler (framework error middleware, job runner, or `main()`).
3. **Never swallow.** A `catch` block must rethrow, return a typed failure, or log with enough context to act on. Empty `catch {}` is not allowed.
4. **Add context with `cause`.** Wrap low-level errors in a message that names the operation and keep the original as `cause`:
```js
// errors.mjs
export class NotFoundError extends Error {
constructor(message, options) {
super(message, options)
this.name = 'NotFoundError'
}
}
export async function loadUser(repo, id) {
try {
const user = await repo.find(id)
if (!user) throw new NotFoundError(`user ${id} not found`)
return user
} catch (error) {
if (error instanceof NotFoundError) throw error
throw new Error(`loadUser(${id}) failed`, { cause: error })
}
}
```
5. **Bound waiting.** Give network and I/O calls a deadline with `AbortSignal.timeout(ms)` (combine with a caller's signal via `AbortSignal.any`). A timeout rejects with a `DOMException` named `TimeoutError`.
```js
// fetch-json.mjs
export async function fetchJson(url, { timeoutMs = 5000, signal } = {}) {
const deadline = AbortSignal.timeout(timeoutMs)
const res = await fetch(url, { signal: signal ? AbortSignal.any([signal, deadline]) : deadline })
if (!res.ok) throw new Error(`GET ${url} returned ${res.status}`)
return res.json()
}
```
6. **Choose the right combinator.** `Promise.all` rejects on the first failure (other work keeps running unless you abort it); use it when all results are required. Use `Promise.allSettled` when partial success is acceptable and report each rejection. `Promise.any` rejects with an `AggregateError` whose `errors` array holds every reason.
7. **Do not mix styles.** Convert callback APIs with `node:util` `promisify` or use the `fs/promises`-style APIs. Never call a callback and also return a promise from the same function.
8. **Process-level handlers are a last resort.** Since Node.js 15 an unhandled rejection crashes the process by default. Keep that behavior: in `process.on('uncaughtException')` / `'unhandledRejection'` handlers, log synchronously with the error and stack, then exit with a non-zero code and let the supervisor restart the process. Do not continue serving requests after an uncaught exception.
9. **Use the project's logger.** Log the error object (not just `error.message`) so the stack and `cause` chain are kept. Do not log secrets or full request bodies.
## Test the failure paths
A test must fail when nothing throws. Use `assert.rejects`, not a `try`/`catch` with an assertion inside.
```js
// errors.test.mjs
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { loadUser, NotFoundError } from './errors.mjs'
test('missing user rejects with NotFoundError', async () => {
await assert.rejects(loadUser({ find: async () => null }, '42'), NotFoundError)
})
test('driver errors are wrapped with cause', async () => {
const boom = new Error('connection reset')
await assert.rejects(loadUser({ find: async () => { throw boom } }, '42'), (error) => {
assert.equal(error.cause, boom)
return true
})
})
```
## Verify before finishing
- Run the tests (`node --test` or the project's runner) and include at least one rejection test per new error path.
- Run lint with the floating-promise rule if the project has it.
- `grep -rnE "catch \(\w*\) \{\s*\}" src` finds no empty catch blocks.
- Start the service and confirm a forced failure (for example, an unreachable dependency) produces one logged error with its `cause`, not a hang or a silent success.
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
coding
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Hardening a Node.js 24 service whose outbound calls can hang and whose errors lose context before reaching logs.
services/user.mjs has loadUser(repo, id) that catches every error and returns null, fetchProfile(url) uses fetch with no timeout, and tests use try { await fn(); assert.fail() } catch (e) { assert.ok(e) }. Fix error handling and tests.Illustrative; not a recorded model run. loadUser rethrows a NotFoundError for missing users and wraps driver errors as new Error('loadUser(<id>) failed', { cause }); fetchProfile uses AbortSignal.timeout combined with any caller signal via AbortSignal.any and throws on non-2xx; tests use assert.rejects with an error class or validator; process handlers log and exit non-zero; no empty catch blocks.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/nodejs-async-error-handling.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: "Node.js Async Error Handling: Propagation, Timeouts and Rejection Tests project conventions"
globs: "**/*"
alwaysApply: false
---
# Node.js Async Error Handling
Applies to: promises, `async`/`await`, timeouts and process-level error handling in Node.js services and scripts.
Version baseline: checked against the Node.js 24 documentation. Read `package.json` (`engines`, `type`) first. `AbortSignal.timeout()` needs Node.js 16.14+ and `AbortSignal.any()` needs 18.17+ (or 20.3+ on the 20 line); on older runtimes fall back to an `AbortController` with `setTimeout`.
## Rules
1. **Every promise is awaited, returned or explicitly handled.** A floating promise loses its error. If fire-and-forget is intended, attach `.catch()` that logs, and say why in a comment. Enable `@typescript-eslint/no-floating-promises` or an equivalent lint rule when the project uses TypeScript.
2. **Catch only where you can act.** Wrap with `try`/`catch` when you can retry, fall back, translate the error into a domain error or HTTP status, or add context. Otherwise let it propagate to the central handler (framework error middleware, job runner, or `main()`).
3. **Never swallow.** A `catch` block must rethrow, return a typed failure, or log with enough context to act on. Empty `catch {}` is not allowed.
4. **Add context with `cause`.** Wrap low-level errors in a message that names the operation and keep the original as `cause`:
```js
// errors.mjs
export class NotFoundError extends Error {
constructor(message, options) {
super(message, options)
this.name = 'NotFoundError'
}
}
export async function loadUser(repo, id) {
try {
const user = await repo.find(id)
if (!user) throw new NotFoundError(`user ${id} not found`)
return user
} catch (error) {
if (error instanceof NotFoundError) throw error
throw new Error(`loadUser(${id}) failed`, { cause: error })
}
}
```
5. **Bound waiting.** Give network and I/O calls a deadline with `AbortSignal.timeout(ms)` (combine with a caller's signal via `AbortSignal.any`). A timeout rejects with a `DOMException` named `TimeoutError`.
```js
// fetch-json.mjs
export async function fetchJson(url, { timeoutMs = 5000, signal } = {}) {
const deadline = AbortSignal.timeout(timeoutMs)
const res = await fetch(url, { signal: signal ? AbortSignal.any([signal, deadline]) : deadline })
if (!res.ok) throw new Error(`GET ${url} returned ${res.status}`)
return res.json()
}
```
6. **Choose the right combinator.** `Promise.all` rejects on the first failure (other work keeps running unless you abort it); use it when all results are required. Use `Promise.allSettled` when partial success is acceptable and report each rejection. `Promise.any` rejects with an `AggregateError` whose `errors` array holds every reason.
7. **Do not mix styles.** Convert callback APIs with `node:util` `promisify` or use the `fs/promises`-style APIs. Never call a callback and also return a promise from the same function.
8. **Process-level handlers are a last resort.** Since Node.js 15 an unhandled rejection crashes the process by default. Keep that behavior: in `process.on('uncaughtException')` / `'unhandledRejection'` handlers, log synchronously with the error and stack, then exit with a non-zero code and let the supervisor restart the process. Do not continue serving requests after an uncaught exception.
9. **Use the project's logger.** Log the error object (not just `error.message`) so the stack and `cause` chain are kept. Do not log secrets or full request bodies.
## Test the failure paths
A test must fail when nothing throws. Use `assert.rejects`, not a `try`/`catch` with an assertion inside.
```js
// errors.test.mjs
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { loadUser, NotFoundError } from './errors.mjs'
test('missing user rejects with NotFoundError', async () => {
await assert.rejects(loadUser({ find: async () => null }, '42'), NotFoundError)
})
test('driver errors are wrapped with cause', async () => {
const boom = new Error('connection reset')
await assert.rejects(loadUser({ find: async () => { throw boom } }, '42'), (error) => {
assert.equal(error.cause, boom)
return true
})
})
```
## Verify before finishing
- Run the tests (`node --test` or the project's runner) and include at least one rejection test per new error path.
- Run lint with the floating-promise rule if the project has it.
- `grep -rnE "catch \(\w*\) \{\s*\}" src` finds no empty catch blocks.
- Start the service and confirm a forced failure (for example, an unreachable dependency) produces one logged error with its `cause`, not a hang or a silent success.
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.