docs(error-handling): explain empty catch rules with examples

This commit is contained in:
Turtle committed 2026-11-11 12:47:01 +08:00
1 parent 33e2285547
commit 603ed7e7d0
6 files changed
+48 -8

No files matched your search

@@ -9,8 +9,8 @@
en: a89b84c7052329b4
zh: 9c511a0b4ee3f1ef
/agent-note-reject-silent-empty-catch-clauses/decision:
en: 1b9199240c84fb54
zh: 155f0381f09effa1
en: 0392fb5d5cc3b387
zh: c4219e43bded8ce6
/agent-note-reject-silent-empty-catch-clauses/alternatives-considered:
en: 65d05680072f8797
zh: e160d37d8ece30ad
@@ -10,7 +10,7 @@ An empty `catch` discards every failure of its `try`, including defects the auth
## Decision
The [checker](../../../../scripts/verify-empty-catch.ts), exposed as `pnpm run verify-empty-catch`, parses first-party JavaScript and TypeScript with the TypeScript syntax tree and reports an empty clause, one whose body holds no statement other than `;`, that is unnamed, unexplained, or wraps a multi-statement `try`. A bare `_` counts as unnamed; lint requires an unused binding to start with `_`, so a conforming name such as `_alreadyGone` states the expected failure. A clause body with any other statement is out of scope because syntax cannot show whether it handles the error. The checker establishes the form; review establishes that the name and the reason are true, using the guidance in [dsh-error-handling](../../../skills/dsh-error-handling/SKILL.md#catch-recover-or-stop).
The [checker](../../../../scripts/verify-empty-catch.ts), exposed as `pnpm run verify-empty-catch`, parses first-party JavaScript and TypeScript with the TypeScript syntax tree and reports an empty clause, one whose body holds no statement other than `;`, that is unnamed, unexplained, or wraps a multi-statement `try`. A bare `_` counts as unnamed; lint requires an unused binding to start with `_`, so a conforming name such as `_alreadyGone` states the expected failure. A clause body with any other statement is out of scope because syntax cannot show whether it handles the error. The checker establishes the form; review establishes that the name and the reason are true, using the guidance in [dsh-error-handling](../../../skills/dsh-error-handling/SKILL.md#empty-catch-clauses).
Existing clauses have an exact baseline keyed by repository-relative path, a SHA-256 digest of the clause's syntax tokens together with its broken conditions, and occurrence count. Including the broken conditions makes turning a recorded one-statement `try` into a wider one, or deleting a recorded reason, a new finding, while edits inside the `try` that keep its conditions keep the clause's identity. The baseline follows the [unknown-cast inventory](2026-09-19-no-unknown-casts.md), and both checkers share [the inventory module](../../../../scripts/baseline-inventory.ts): baseline edits only delete entries or decrease counts, `--prune` removes retired entries and refuses to write while new findings exist, and no command adds an allowance. Unlike the unknown-cast inventory, which requires resolving an assertion before moving it to an unlisted file, moving a file that holds recorded clauses renames its baseline key in the same change, because narrowing a recorded `try` belongs to its owner rather than to the change that moves the file.
@@ -10,7 +10,7 @@ Status: implemented
## 决策
[检查器](../../../../scripts/verify-empty-catch.ts)通过 `pnpm run verify-empty-catch` 运行,使用 TypeScript 语法树解析第一方 JavaScript 和 TypeScript,并报告未命名、未说明原因或包裹多语句 `try` 的空子句;空子句指主体中除 `;` 外不含任何语句的子句。单独的 `_` 视为未命名;lint 要求未使用的绑定以 `_` 开头,因此 `_alreadyGone` 这类符合要求的名称可以说明预期的失败。主体含有其他语句的子句不属于此规则的范围,因为语法无法表明它是否处理了错误。检查器确认形式;审查依据 [dsh-error-handling](../../../skills/dsh-error-handling/SKILL.md#catch-recover-or-stop) 中的指引确认名称和原因属实。
[检查器](../../../../scripts/verify-empty-catch.ts)通过 `pnpm run verify-empty-catch` 运行,使用 TypeScript 语法树解析第一方 JavaScript 和 TypeScript,并报告未命名、未说明原因或包裹多语句 `try` 的空子句;空子句指主体中除 `;` 外不含任何语句的子句。单独的 `_` 视为未命名;lint 要求未使用的绑定以 `_` 开头,因此 `_alreadyGone` 这类符合要求的名称可以说明预期的失败。主体含有其他语句的子句不属于此规则的范围,因为语法无法表明它是否处理了错误。检查器确认形式;审查依据 [dsh-error-handling](../../../skills/dsh-error-handling/SKILL.md#empty-catch-clauses) 中的指引确认名称和原因属实。
现有子句使用精确基线记录,键由仓库相对路径、子句语法 token 连同其违反条件的 SHA-256 摘要及出现次数组成。摘要包含违反条件,因此把已记录的单语句 `try` 扩大为多语句 `try`,或删除已记录的原因,都会产生新的检查发现;而在 `try` 内部进行不改变其违反条件的修改,不改变子句的标识。基线沿用 [unknown 类型断言清单](2026-09-19-no-unknown-casts.zh.md)的做法,两个检查器共用[清单模块](../../../../scripts/baseline-inventory.ts):基线修改只能删除条目或减少次数,`--prune` 删除已失效的条目并在存在新发现时拒绝写入,且没有任何命令可以添加放行。unknown 类型断言清单要求先解决断言,才能将其移至未登记的文件;与之不同,移动包含已记录子句的文件时,须在同一变更中重命名其基线键,因为收窄已记录的 `try` 由其所属模块负责,而不属于移动文件的变更。
+41 -1
View File
@@ -34,7 +34,47 @@ For each failure, define handling and reporting owners, containment, and guarant
Catching limits exception propagation, not mutations. Only the affected state's owner can establish safe continuation. Otherwise stop dependent work, discard invalid state or instances, or escalate. Logging alone is not recovery. Retries require safe repetition, cancellation, and an explicit owner; finite operations need budgets, while continuing supervision needs lifecycle ownership and observable degradation.
An empty `catch` discards every failure of its `try`, so it is acceptable only when each such failure leaves the owner's state valid and no caller can act on it, such as best-effort cleanup after a primary failure. Keep the `try` to one statement, bind the error to an underscore-prefixed name that states the expected failure, such as `_alreadyGone` (lint requires the prefix on an unused binding; a bare `_` counts as unnamed), and explain in the `catch` block why the state stays valid. When only some failures are acceptable, test `code` or `name` and rethrow the rest; an unconditional discard also reports defects as success. [`verify-empty-catch`](../../../scripts/verify-empty-catch.ts) enforces the form; review checks that the name and reason are true.
### Empty catch clauses
An empty `catch` has no statement other than `;` in its block, and it discards every failure its `try` raises. Use one only when every such failure leaves the owner's state valid and no caller could act on it, such as failing to remove a temporary file that nothing reads. A `catch` that logs, reports, rethrows, or returns a fallback is not empty, and the rules below do not apply to it. [`verify-empty-catch`](../../../scripts/verify-empty-catch.ts) checks every `try`/`catch` statement in first-party JavaScript and TypeScript, including tests; it does not check `promise.catch()` callbacks. The checker checks the form; review checks that the name and the reason are true.
**The `try` holds one statement.** One statement means one syntactic statement, such as one call or one assignment, however many lines it spans; it does not mean one line. With several statements, the reason covers one expected failure while the clause also discards the others, including defects such as a `TypeError`, and a failure in an early statement skips the later ones while the caller sees success:
```ts
// Rejected: three statements in one try.
try {
await unlink(tempFile)
registry.delete(id)
emit('removed', id)
} catch (_cleanupFailed) {
// A leftover temporary file holds no state anything reads.
}
// Accepted: only the unlink failure is discarded.
try {
await unlink(tempFile)
} catch (_cleanupFailed) {
// A leftover temporary file holds no state anything reads.
}
registry.delete(id)
emit('removed', id)
```
When several statements each tolerate a failure, give each its own `try` and reason. The checker counts one block or one compound statement, such as one `if`, as one statement; review rejects such a `try` when it contains several operations.
**The binding names the expected failure.** Write `catch (_cleanupFailed)`, not `catch {}` or `catch (_)`. Lint requires an unused binding to start with `_`, and a bare `_` names nothing.
**A comment states why discarding the failure is safe.** Put it in the `catch` block or after the clause's closing `}` on the same line. A comment inside the `try` block or above `try` does not count. `// ignore` and `// expected` restate the empty block; say which failure is expected and why the state stays valid.
**Accept only some failures by testing them.** When only some failures are safe, such as a missing file while a permission error must still surface, write a non-empty `catch` that tests `code` or `name` and rethrows the rest; the checker does not check such a clause.
```ts
try {
await unlink(tempFile)
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
```
## Localized, actionable, visible reports
+2 -2
View File
@@ -173,8 +173,8 @@ describe('empty catch inventory', () => {
const root = fixture()
write(root, sourcePath, broken)
const skillPath = '.agents/skills/dsh-error-handling/SKILL.md'
expect(() => verifyEmptyCatch(root)).toThrow(`(see ${skillPath}#catch-recover-or-stop)`)
expect(readFileSync(join(import.meta.dirname, '..', skillPath), 'utf8')).toMatch(/^## Catch, recover, or stop$/mu)
expect(() => verifyEmptyCatch(root)).toThrow(`(see ${skillPath}#empty-catch-clauses)`)
expect(readFileSync(join(import.meta.dirname, '..', skillPath), 'utf8')).toMatch(/^### Empty catch clauses$/mu)
})
it('requires pruning retired counts while preserving the remaining clause', () => {
+1 -1
View File
@@ -169,7 +169,7 @@ const gate: InventoryGate<EmptyCatch> = {
baselinePath: 'scripts/empty-catch.baseline.json',
scan: scanEmptyCatches,
rejection: 'an empty catch must name the discarded error, state why it needs no handling,'
+ ' and keep its try to one statement (see .agents/skills/dsh-error-handling/SKILL.md#catch-recover-or-stop).',
+ ' and keep its try to one statement (see .agents/skills/dsh-error-handling/SKILL.md#empty-catch-clauses).',
describe: finding => `${finding.file}:${String(finding.line)} (${finding.defects.join(', ')})`,
success: count => `verify-empty-catch: no new silent catches; ${String(count)} recorded clauses remain.`,
}