Narrow try/catch by error kind: a catch handles only what it doesn't rethrow #18

Merged
sionzee merged 1 commit from catch-narrowing into promise-returning-functions 2026-11-03 21:42:15 +01:00
Owner

Stacked on #11 (promise-returning-functions, itself on #5): it builds on #11's per-kind thrown/rejected tracking in project.rs. Review #5 and #11 first; this PR's own change is the last commit.

Closes the third item of README "Known gaps": any catch counted as handling every error. if (e instanceof NotFound) return x; throw e; hid Forbidden from the analysis, catch (e) { throw e } looked like a handler, and try { ... } finally { ... } without a catch counted as one too.

What changed

  • Reading the catch (analyze.rs, catch_rethrows): for each catch (e), when does it rethrow e? Followed through blocks, if/else, return, throw e (and throw of something else, which handles e), with conditions built from e instanceof X (X or ns.X), !, &&, ||. Any other test, and loops / switch / labels / nested try that contain a throw e, count as maybe rethrowing (three-valued logic). A catch that never rethrows handles everything (as before); one that always does, and finally without catch, handle nothing; the rest are recorded per site (tries).
  • Deciding per kind (project.rs): e instanceof X is evaluated for each PropagateError kind along the thrown class's extends chain, across files and re-exports (Gone extends NotFound is caught by instanceof NotFound, not the other way round; instanceof PropagateError / Error catch all kinds). A kind is caught only if the catch's rethrow condition is definitely false for it; otherwise it keeps propagating.
  • safe-ts check's map lists, per call, only the kinds caught there; the others are reported or propagate as usual. Works with #11's rules: a rejection is only caught by a try it is awaited in.
  • Other failures (built-ins, feature-pack library calls, legacy code) inside a narrowing try are decided in the whole-program pass: handled only if the catch keeps them whatever they are, or keeps instanceof Error; a test against a project PropagateError class is known not to match them. So catch (e) { if (e instanceof NotFound) return; throw e; } around JSON.parse now reports unhandled-failure.

Rule change to review: no-throw and throw e

throw e of the unchanged catch (e) binding is no longer a no-throw. Without that, the else throw e pattern this item asks to understand can't be written in checked code at all. It stays sound: the try is now known not to handle what is rethrown, so it is reported where it starts (the no-throw page's rethrow example now shows the unhandled-failure on JSON.parse instead). Reassigned bindings (e = ...) and throw of anything else are still no-throw. If you'd rather keep no-throw strict, this hunk can be dropped and the narrowing still applies to legacy code and to the map.

Not covered (documented in README "Known gaps" and uncaught-propagation)

Tests other than instanceof (e.name === ..., isRetryable(e)), aliases of e, and loops/switch in a catch aren't read in detail: if they can reach throw e, every kind counts as rethrown. For built-in and library failures the error class isn't tracked, so if (e instanceof SyntaxError) return; throw e; around JSON.parse is still reported (a false positive, in the safe direction). There is no docs/overview.md in the repo.

Tests

  • New fixture tests/fixtures/catches: else throw, early return then throw e, negated test with ns.X, ||, subclass-only test, instanceof PropagateError, a handled branch that falls through to the rethrow, an unknown test, a catch without rethrow, finally only, nested tries, async with await, and JSON.parse / legacy calls under narrowing catches (reported when rethrown, not when kept). Fixture throws: catch (e) { throw e } now propagates both kinds and is not a no-throw (it previously expected caught, encoding the gap). Both fail against #11's code (checked by restoring src from that branch).
  • Docs: new checked examples in the errors guide (good) and uncaught-propagation (bad); the no-throw rethrow example changed as above.
  • cargo nextest run --workspace: 94 passed, 1 failed: the pre-existing features fixture failure on main (createDecipheriv, main.ts:55), unrelated.
  • npm run check (demo): output identical to main. safe-ts check examples/vue/src/main.ts: no problems.
  • npm run test:vite, npm run test:docs: passed.
  • npm run test:std: 115/116; feature-node manifest test depends on the local Node version (v26.13.0), fails the same on main.

🤖 Generated with Claude Code

**Stacked on #11** (`promise-returning-functions`, itself on #5): it builds on #11's per-kind thrown/rejected tracking in `project.rs`. Review #5 and #11 first; this PR's own change is the last commit. Closes the third item of README "Known gaps": any `catch` counted as handling every error. `if (e instanceof NotFound) return x; throw e;` hid `Forbidden` from the analysis, `catch (e) { throw e }` looked like a handler, and `try { ... } finally { ... }` without a `catch` counted as one too. ## What changed - **Reading the catch** (`analyze.rs`, `catch_rethrows`): for each `catch (e)`, when does it rethrow `e`? Followed through blocks, `if`/`else`, `return`, `throw e` (and `throw` of something else, which handles `e`), with conditions built from `e instanceof X` (`X` or `ns.X`), `!`, `&&`, `||`. Any other test, and loops / `switch` / labels / nested `try` that contain a `throw e`, count as *maybe* rethrowing (three-valued logic). A catch that never rethrows handles everything (as before); one that always does, and `finally` without `catch`, handle nothing; the rest are recorded per site (`tries`). - **Deciding per kind** (`project.rs`): `e instanceof X` is evaluated for each `PropagateError` kind along the thrown class's `extends` chain, across files and re-exports (`Gone extends NotFound` is caught by `instanceof NotFound`, not the other way round; `instanceof PropagateError` / `Error` catch all kinds). A kind is caught only if the catch's rethrow condition is definitely false for it; otherwise it keeps propagating. - **`safe-ts check`'s map** lists, per call, only the kinds caught there; the others are reported or propagate as usual. Works with #11's rules: a rejection is only caught by a `try` it is awaited in. - **Other failures** (built-ins, feature-pack library calls, legacy code) inside a narrowing `try` are decided in the whole-program pass: handled only if the catch keeps them whatever they are, or keeps `instanceof Error`; a test against a project `PropagateError` class is known not to match them. So `catch (e) { if (e instanceof NotFound) return; throw e; }` around `JSON.parse` now reports `unhandled-failure`. ## Rule change to review: `no-throw` and `throw e` `throw e` of the unchanged `catch (e)` binding is no longer a `no-throw`. Without that, the `else throw e` pattern this item asks to understand can't be written in checked code at all. It stays sound: the `try` is now known not to handle what is rethrown, so it is reported where it starts (the `no-throw` page's rethrow example now shows the `unhandled-failure` on `JSON.parse` instead). Reassigned bindings (`e = ...`) and `throw` of anything else are still `no-throw`. If you'd rather keep `no-throw` strict, this hunk can be dropped and the narrowing still applies to legacy code and to the map. ## Not covered (documented in README "Known gaps" and `uncaught-propagation`) Tests other than `instanceof` (`e.name === ...`, `isRetryable(e)`), aliases of `e`, and loops/`switch` in a `catch` aren't read in detail: if they can reach `throw e`, every kind counts as rethrown. For built-in and library failures the error class isn't tracked, so `if (e instanceof SyntaxError) return; throw e;` around `JSON.parse` is still reported (a false positive, in the safe direction). There is no `docs/overview.md` in the repo. ## Tests - New fixture `tests/fixtures/catches`: `else throw`, early return then `throw e`, negated test with `ns.X`, `||`, subclass-only test, `instanceof PropagateError`, a handled branch that falls through to the rethrow, an unknown test, a catch without rethrow, `finally` only, nested tries, async with `await`, and `JSON.parse` / legacy calls under narrowing catches (reported when rethrown, not when kept). Fixture `throws`: `catch (e) { throw e }` now propagates both kinds and is not a `no-throw` (it previously expected `caught`, encoding the gap). Both fail against #11's code (checked by restoring `src` from that branch). - Docs: new checked examples in the errors guide (`good`) and `uncaught-propagation` (`bad`); the `no-throw` rethrow example changed as above. - `cargo nextest run --workspace`: 94 passed, 1 failed: the pre-existing `features` fixture failure on `main` (`createDecipheriv`, `main.ts:55`), unrelated. - `npm run check` (demo): output identical to `main`. `safe-ts check examples/vue/src/main.ts`: no problems. - `npm run test:vite`, `npm run test:docs`: passed. - `npm run test:std`: 115/116; `feature-node` manifest test depends on the local Node version (v26.13.0), fails the same on `main`. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Any `catch` counted as handling every error, so `if (e instanceof NotFound) return x;
throw e;` hid `Forbidden` from the analysis, `catch (e) { throw e }` looked like a
handler, and even `try { ... } finally { ... }` without a catch counted as one.

Each catch clause is read for when it rethrows its binding: `if`/`else`, `return`,
blocks and `throw e`, with conditions built from `e instanceof X` (`X` or `ns.X`), `!`,
`&&` and `||`. Anything else it can't read (other tests, loops, switch) counts as maybe
rethrowing. The whole-program pass decides `instanceof` per kind along the thrown
class's `extends` chain, across files, so only the kinds a catch really keeps are
removed; the rest keep propagating and the PropagateError map lists, per call, only the
kinds caught there. Built-in, library and legacy failures count as handled only if the
catch keeps them whatever they are (or keeps `instanceof Error`).

`throw e` of the unchanged catch binding is no longer a `no-throw`: without it the
narrowing pattern can't be written in checked code, and what it rethrows is still
reported where it starts, since the try is now known not to handle it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee merged commit a78a284cdb into promise-returning-functions 2026-11-03 21:42:15 +01:00
sionzee deleted branch catch-narrowing 2026-11-03 21:42:15 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!18
No description provided.