Skip to content

fix: close safeTry generator on Err short-circuit so finally blocks run - #697

Open
CHX606 wants to merge 1 commit into
supermacro:masterfrom
CHX606:fix/safe-try-run-finally-on-err
Open

CHX606 wants to merge 1 commit into
supermacro:masterfrom
CHX606:fix/safe-try-run-finally-on-err

Conversation

@CHX606

@CHX606 CHX606 commented Nov 23, 2026

Copy link
Copy Markdown

Fixes #696

Problem

When yield* short-circuits on an Err (or ResultAsync resolving to Err), safeTry previously read the yielded Err from gen.next() and returned immediately without calling gen.return(...). Because the generator remained suspended inside try, any enclosing finally blocks (and using / await using disposers) were never executed.

Solution

  • Store the generator created by body() and close it via gen.return(current.value) while !current.done (repeating if an enclosing finally block itself short-circuits via yield*).
  • In the async branch, return r.value directly when r.done is already true (no extra microtask tick on the non-short-circuit path) and chain asyncGen.return(r.value) otherwise so async finally cleanup completes before the returned ResultAsync settles.
  • Preserve reference identity of the yielded Err instance when finally does not override the completion.

Validation

  • Added 7 unit tests in tests/safe-try.test.ts covering sync yield* err(...), .safeUnwrap(), async yield* errAsync(...) with awaited cleanup, mixed sync err(...) in async function*, nested try ... finally ordering, finally blocks that themselves yield* an Err, and normal-return single-execution controls (6 failing regressions + 1 passing control on unchanged 5ef3a018, all passing after fix).
  • npm run typecheck, npm run lint, npm test (124 passed + test-types), and npm run build (rollup + attw --pack .) all pass.

@changeset-bot

changeset-bot Bot commented Nov 23, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: de9eaf7

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
neverthrow Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

safeTry does not run finally blocks when the body short-circuits on an Err

1 participant