Agent skill

Result Error Handling

by andymai in andymai/brepjs

This skill should be used when working with Result<T,E, BrepError, or error paths in brepjs — deciding whether to throw or return a Result, constructing errors with codes, or handling failures.

Apache-2.0Auto-check passedDevelopment

Install Result Error Handling

skills CLI
$ npx skills add andymai/brepjs --skill result-error-handling -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install andymai/brepjs result-error-handling --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/andymai/brepjs.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.claude/skills/result-error-handling .claude/skills/result-error-handling && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
result-error-handling
GitHub stars
115
Token cost
~4.2k tokens
SKILL.md length
1,287 words
Files
1
Skills in repo
21
Repo updated
First seen
Licence
Apache-2.0

At a glance

This skill should be used when working with Result<T,E, BrepError, or error paths in brepjs — deciding whether to throw or return a Result, constructing errors with codes, or handling failures.

  • Works in 2 steps: BrepError.code is typed string, not the… → The catalog is incomplete: dozens of…
  • Phrases include should this throw
  • SKILL.md covers The two failure channels, Constructing errors, Error codes and Consuming Results, plus 3 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Result Error Handling is an agent skill from andymai/brepjs. This skill should be used when working with Result<T,E, BrepError, or error paths in brepjs — deciding whether to throw or return a Result, constructing errors with codes, or handling failures. Trigger phrases include "should this throw or return err", "Called unwrap() on an Err", "add a new error code", "BrepErrorCode", "kernelCall", "unsupportedError", "BrepWrapperError", "the operation failed silently", "error was swallowed", "how do I unwrap this Result", or writing a new Fns.ts function that can fail.

Its SKILL.md is about 4.2k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Development, covering Error handling. The repository describes itself as: Web CAD library with exact B-Rep geometry. The licence is Apache-2.0.

When your agent uses it

  • Phrases include should this throw
  • Called unwrap() on an Err
  • Add a new error code
  • UnsupportedError

Example prompts

  • “should this throw or return err”
  • “Called unwrap() on an Err”
  • “add a new error code”
  • “/result-error-handling”

Workflow steps

2 steps, taken from the first numbered list in SKILL.md.

  1. BrepError.code is typed string, not the union — a raw-string typo compiles fine. The catalog is advisory; checking it is on the author.
  2. The catalog is incomplete: dozens of codes exist in src only as raw string literals (FILLET_FAILED, WIRE_NOT_CLOSED, THREAD_INVALID_PITCH…

What it can do on your machine

Read from SKILL.md and the folder at commit 6e20740. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Result Error Handling loads about 4.2k tokens when it runs. Until then it costs about 134 tokens; SKILL.md has 1,287 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~134
When it runs · the whole SKILL.md, loaded when a task matches
~4.2k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from andymai/brepjs at commit 6e20740, republished under its Apache-2.0 licence (© andymai). 1,287 words, ~4,171 tokens.

Download SKILL.mdSave it as .claude/skills/result-error-handling/SKILL.md (or your agent's skills folder).
name
result-error-handling
description
This skill should be used when working with Result<T,E>, BrepError, or error paths in brepjs — deciding whether to throw or return a Result, constructing errors with codes, or handling failures. Trigger phrases include "should this throw or return err", "Called unwrap() on an Err", "add a new error code", "BrepErrorCode", "kernelCall", "unsupportedError", "BrepWrapperError", "the operation failed silently", "error was swallowed", "how do I unwrap this Result", or writing a new *Fns.ts function that can fail.

Result types and error handling

Every fallible operation in brepjs returns Result<T, BrepError> instead of throwing. The type, all combinators, and the extraction helpers live in src/core/result.ts (zero internal imports — a pure foundation module). Error kinds, the code catalog, and per-kind constructors live in src/core/errors.ts.

The two failure channels

Pick the channel before writing any error-handling code:

SituationChannelMechanism
Expected failure (bad input, kernel op failed, unsupported capability, file won't parse)Resulterr(validationError(...)), kernelCall(...), etc.
Programmer bug / broken invariant ("this can never happen")Throwbug(location, message) from src/utils/bug.ts — throws BrepBugError, never meant to be caught
Out-of-bounds index that is valid by construction (under noUncheckedIndexedAccess)ThrowsafeIndex(arr, i, context) in src/core/errors.ts — the sanctioned arr[i]! replacement
Cooperative cancellationThrowif (signal?.aborted) throw signal.reason (see src/topology/booleanFns.ts)

The rule for Layers 2–3 (.claude/commands/new-operation.md, CLAUDE.md): never throw for expected failures — return ok(...) or err(...). No ESLint rule enforces this mechanically, so it must be applied by discipline in every new *Fns.ts function. The exceptions above (bug(), safeIndex(), abort rethrows) are the only tolerated throws.

The one sanctioned Result→throw boundary is the fluent shape() facade in src/topology/wrapperFns.ts: every chainable method funnels through an internal unwrapOrThrow that throws BrepWrapperError on Err. See "The throwing boundary" below.

Constructing errors

Prefer kernelCall for kernel operations

src/core/kernelCall.ts is the standard error-construction path in *Fns.ts files. It wraps try/catch, casts the result, translates cryptic OCCT messages, and auto-attaches a suggestion:

ts
// src/topology/shapeFns.ts
return kernelCall(
  () => getKernel().downcast(shape.wrapped),
  BrepErrorCode.CLONE_FAILED,
  'Failed to clone shape'
) as Result<T>;

Three variants:

HelperReturnsUse when
kernelCall(fn, code, message, kind?)Result<AnyShape>Kernel call returns a KernelShape; auto-runs castShape()
kernelCallRaw<T>(fn, code, message, kind?)Result<T>Kernel call returns anything else (string, number, array)
kernelCallScoped(fn, code, message, kind?)Result<AnyShape>fn(scope) needs intermediate kernel allocations — the DisposalScope is disposed even on the error path (see the memory-and-disposal skill)

On exception, the error message becomes `${message}: ${translated}` where translateKernelError() (src/core/kernelErrorTranslation.ts) maps ~12 cryptic OCCT patterns (BRepAlgoAPI failures, fillet radius too large, degenerate geometry, ...) into actionable text with the original appended as (kernel: ...). Translation applies only when kind is 'KERNEL_OPERATION' (the default). ERROR_CODE_SUGGESTIONS in the same file maps a dozen codes (FUSE_FAILED, CUT_FAILED, *_NOT_3D, SWEEP_FAILED, LOFT_FAILED, DRAFT_FAILED, ...) to suggestion strings that ride along automatically.

Manual construction: pick the kind-matching constructor

BrepError is a plain object: { kind, code, message, suggestion?, cause?, metadata? } (src/core/errors.ts). There are 9 kinds, each with a constructor sharing the signature (code, message, cause?, metadata?, suggestion?):

KindConstructorUse for
VALIDATIONvalidationErrorBad input parameters (check these first, before touching the kernel)
KERNEL_OPERATIONkernelErrorKernel op failed (prefer kernelCall unless building the error by hand)
TYPE_CASTtypeCastErrorResult was not the expected shape type (e.g. boolean returned non-3D)
COMPUTATIONcomputationErrorGeometric computation failed (intersection, skeleton, center of mass)
IOioErrorImport/export failure
QUERYqueryErrorShape query failure (e.g. finder not unique)
MODULE_INITmoduleInitErrorInitialisation failure
UNSUPPORTEDunsupportedErrorCapability not supported by the current kernel (ADR-0006) — see the kernel-abstraction skill
SKETCHER_STATEsketcherStateErrorCurrently unused in src; exists for sketcher state transitions

Always thread context through:

  • cause: the original exception. Dropping it destroys kernel diagnostics.
  • metadata: structured context. Real example from src/topology/modifierFns.ts:
ts
return err(
  kernelError('FILLET_FAILED', `Fillet operation failed: ${raw}`, e, {
    operation: 'fillet',
    edgeCount: selectedCount,
    radius,
  })
);
  • suggestion: a recovery hint. The shape() wrapper folds it into the thrown message ("...\nSuggestion: ..."), so it reaches users.

Error codes

BrepErrorCode (src/core/errors.ts) is an as const catalog of ~124 codes grouped by category, with a matching literal-union type. Use BrepErrorCode.X instead of a raw string whenever the code exists — but know two caveats:

  1. BrepError.code is typed string, not the union — a raw-string typo compiles fine. The catalog is advisory; checking it is on the author.
  2. The catalog is incomplete: dozens of codes exist in src only as raw string literals (FILLET_FAILED, WIRE_NOT_CLOSED, THREAD_INVALID_PITCH, and whole families). Grep before assuming a code is new.

To add a new code:

  1. Add the constant to BrepErrorCode in src/core/errors.ts under its category group (kernel-op, validation, IO, ...).
  2. Use it via the kind-matching constructor, or pass it to kernelCall.
  3. Optionally add an entry to ERROR_CODE_SUGGESTIONS in src/core/kernelErrorTranslation.ts so kernelCall auto-attaches a recovery hint.
  4. Optionally add a row to the tables in docs/errors.md (hand-maintained, no CI check — see the staleness warning below).
Show full SKILL.md (620 more words)Show less

Consuming Results

NeedUseNotes
Branch on outcomeisOk(r) / isErr(r)Type guards; narrow to Ok<T> / Err<E>
Handle both arms as an expressionmatch(r, { ok: v => ..., err: e => ... })
Extract in a test or scriptunwrap(r)Throws with [kind] CODE: message formatting on Err
Extract with fallbackunwrapOr(r, default) / unwrapOrElse(r, fn)Never use to paper over failures the caller should see
Chain fallible stepsandThen (alias flatMap), or pipeline(input).then(fn).then(fn).resultBoth short-circuit on first Err
Transform value / errormap / mapErr / mapBoth
Combine manycollect(results) (alias all), zip(a, b)collect short-circuits on first Err; zip is re-exported from src/index.ts as zipResults
Side-effect without consumingtap / tapErrtapErr is the idiomatic "log and pass through"
Wrap throwing codetryCatch(fn, mapError) / tryCatchAsyncUse at boundaries with throwing third-party code
Void successOK constant (Ok<Unit>)For operations with nothing to return
Nullable → ResultfromNullable(value, errorFn)

The unwrap() policy (CLAUDE.md, docs/getting-started.md): sanctioned in tests (the standard extractor), scripts/examples, and internal calls that are infallible by construction — e.g. unwrap(resolvePlane('XY', origin)) in src/core/planeOps.ts, where the input is a known-valid literal. Never use it on a user-facing fallible path in production code; use isOk()/match() there.

Note the kernel-free subpath brepjs/core (src/core.ts) exports only a subset of combinators — no pipeline, mapBoth, tap/tapErr, fromNullable, or/orElse, zip. The full set is on the main brepjs entry.

For Results inside disposal scopes, withScopeResult / withScopeResultAsync in src/core/disposal.ts combine DisposalScope cleanup with a Result-returning body (documented in src/core/README.md).

The throwing boundary: shape() and BrepWrapperError

The fluent shape() wrapper (src/topology/wrapperFns.ts) auto-unwraps every Result and throws BrepWrapperError on Err. The class carries code, kind, suggestion?, metadata?, and its message includes the suggestion when present. Gotcha: error.name is set to 'BrepError' even though the class is BrepWrapperError — match with instanceof BrepWrapperError (exported from src/index.ts), not by name. The catch pattern is shown in docs/cheat-sheet.md.

Escape hatches on the wrapper: .applyResult(fn) unwraps a user-supplied Result-returning function; .done() / .val exit back to plain handles. docs/which-api.md frames the fluent-vs-functional trade-off around exactly this Result-handling difference.

Silent failures: symptom → cause → fix

SymptomLikely causeFix
Operation "succeeds" but geometry is missing/wrong downstreamAn Err was discarded (result assigned, never checked)Check every Result; use tapErr to log, match to handle, or propagate with early return on isErr
Failure invisible until far awayunwrapOr(r, fallback) masking a real errorReserve unwrapOr for genuinely optional values; otherwise propagate the Err
Called unwrap() on an Err: [KERNEL_OPERATION] ...unwrap() on a fallible pathRead the formatted [kind] CODE: message; handle with isOk/match at that call site
Error message is cryptic OCCT text with no contextHand-rolled try/catch instead of kernelCall, or cause droppedRoute kernel calls through kernelCall/kernelCallRaw/kernelCallScoped; always pass the caught exception as cause
Plain Error thrown from a *Fns.ts functionLayer 2+ rule violatedConvert to err(<kind>Error(code, message, cause)); reserve throws for bug()
Typo'd error code compiles and shipscode is typed stringUse BrepErrorCode.X; add the constant if it does not exist
Async code fails against the wrong kernel with confusing errorswithKernel(id, fn) is sync-only — after the first await the callback silently uses the default kernelUse getKernel(id) directly in async code (CLAUDE.md gotcha)
Bad geometry with an Ok resultNot an error-channel problem — the kernel produced a valid-but-wrong shapeSee the debugging-geometry skill

Additional resources

  • src/core/result.ts — the full Result API; short and readable, treat it as the reference.
  • src/core/errors.ts — kinds, catalog, constructors, safeIndex; ground truth for codes.
  • src/core/kernelCall.ts and src/core/kernelErrorTranslation.ts — the standard construction path and translation/suggestion tables.
  • docs/errors.md — user-facing per-code reference with recovery advice. Partially stale: its kind list omits UNSUPPORTED, and its code tables drift from errors.ts in both directions. When they disagree, src/core/errors.ts wins.
  • The adding-operations skill — the full recipe for a new *Fns.ts operation (validate → err(validationError(...)) → kernelCall → ok).
  • The writing-tests skill — asserting on Err results and using unwrap in tests.

© andymai, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in .claude/skills/result-error-handling of andymai/brepjs.

Open the folder on GitHubat commit 6e20740

Compare with similar skills

Result Error Handling next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Result Error Handling compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Result Error Handling this skillandymai/brepjs115—~4.2kAutomated safety check: PassApache-2.0
Mole Bug Patternstw93/Mole70k—~2kAutomated safety check: PassGPL-3.0
Native Data FetchingCherryHQ/cherry-studio-app4k6 repos~2.9kAutomated safety check: NotesMIT
Rust Best Practicesfarm-fe/farm5.6k3 repos~1.1kAutomated safety check: PassMIT
R Function Input Validationtidyverse/dplyr5.1k1 repos~2.3kAutomated safety check: PassCustom licence
Next Best Practicesvercel-labs/openreview1.7k18 repos~1kAutomated safety check: PassNone

Similar skills

  • A catalog of recurring bug shapes in the Mole Mac cleaner, used to review safety-sensitive diffs for deletion safety, unbounded commands, shell traps and weak tests.

    70k GitHub stars~2k tokensUpdated today
    DevelopmentAuto-check passed
  • Native Data Fetching

    CherryHQ/cherry-studio-app

    A skill your agent uses when implementing or debugging ANY network request, API call, or data fetching.

    4k GitHub starsUsed in 6 repos~2.9k tokens
    DevelopmentAuto-check: notes
  • Guide for writing idiomatic Rust code based on Apollo GraphQL's best practices handbook.

    5.6k GitHub starsUsed in 3 repos~1.1k tokens
    DevelopmentAuto-check passed
  • Validates arguments of exported R functions with the standalone check_* type checkers from rlang, in tidyverse style with clear error messages.

    5.1k GitHub starsUsed in 1 repo~2.3k tokens
    DevelopmentAuto-check passed
  • Next Best Practices

    vercel-labs/openreview

    Official

    Next.js best practices - file conventions, RSC boundaries, data patterns, async APIs, metadata, error handling, route handlers, image/font optimization, bundling

    1.7k GitHub starsUsed in 18 repos~1k tokens
    DevelopmentAuto-check passed
  • Error Handling

    microsoft/data-formulator

    Official

    统一错误处理系统。在添加 API 端点、修改错误处理、添加前端 API 调用、编写错误相关测试时使用. An agent skill from microsoft/data-formulator.

    18k GitHub stars~3.8k tokensUpdated yesterday
    DevelopmentAuto-check passed

More from andymai/brepjs

All 21 skills in this repo
  • Implement

    andymai/brepjs

    A skill your agent uses when authoring or editing a brepjs .brep.ts part — writing the geometry with the functional API (box, cylinder, fuse, cut, fillet, sketch→extrude…), declaring an expected…

    115 GitHub stars~3.4k tokensUpdated yesterday
    Auto-check passed
  • Memory And Disposal

    andymai/brepjs

    This skill should be used when managing WASM handle lifetimes or hunting memory leaks in brepjs — when a task mentions "createHandle() without using keyword risks WASM memory leak"…

    115 GitHub stars~3.1k tokensUpdated yesterday
    Auto-check passed
  • Polish

    andymai/brepjs

    A skill your agent uses when a valid brepjs part should look designed rather than glued-from-primitives (products, toys, mechanisms, anything a human eyeballs), and when exporting/handing off the…

    115 GitHub stars~588 tokensUpdated yesterday
    Auto-check passed
  • Wasm Interop

    andymai/brepjs

    This skill should be used when working across the JS/WASM boundary in brepjs — writing or debugging code in src/kernel/occt, src/kernel/occtWasm, or src/kernel/brepkit, or diagnosing symptoms like…

    115 GitHub stars~3k tokensUpdated yesterday
    Auto-check passed
  • Writing Tests

    andymai/brepjs

    This skill should be used when writing, running, or fixing tests in the brepjs repository — when a task says "add a test", "write a regression test", "tests are failing", "test timed out", "coverage…

    115 GitHub stars~4.3k tokensUpdated yesterday
    Auto-check passed
  • Adding Operations

    andymai/brepjs

    This skill should be used when adding or extending a geometric shape operation in brepjs — the end-to-end recipe once the target module is chosen (which is decided by architecture-navigation) — when…

    115 GitHub stars~4.4k tokensUpdated yesterday
    Auto-check passed

Categories

Questions about Result Error Handling

What does Result Error Handling do?

This skill should be used when working with Result<T,E, BrepError, or error paths in brepjs — deciding whether to throw or return a Result, constructing errors with codes, or handling failures. Result Error Handling is an agent skill from andymai/brepjs. This skill should be used when working with Result<T,E, BrepError, or error paths in brepjs — deciding whether to throw or return a Result, constructing errors with codes, or handling failures.

When should I use Result Error Handling?

Result Error Handling fits situations like: phrases include should this throw; called unwrap() on an Err; add a new error code; unsupportedError.

How do I install Result Error Handling in Claude Code?

Run `npx skills add andymai/brepjs --skill result-error-handling -a claude-code`. Or copy the skill folder (.claude/skills/result-error-handling in andymai/brepjs) into .claude/skills/result-error-handling in your project. Claude Code loads it when a task matches its description.

How do I install Result Error Handling in Codex?

Run `npx skills add andymai/brepjs --skill result-error-handling -a codex`. Or copy the skill folder (.claude/skills/result-error-handling in andymai/brepjs) into .agents/skills/result-error-handling in your project. Codex loads it when a task matches its description.

Can I use Result Error Handling in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add andymai/brepjs --skill result-error-handling -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/result-error-handling, .gemini/skills/result-error-handling, .github/skills/result-error-handling and .opencode/skills/result-error-handling in your project.

What does Result Error Handling need to run?

SKILL.md names no scripts, command-line tools or credentials: Result Error Handling is instructions for the agent only.

Does Result Error Handling access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Result Error Handling safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Result Error Handling use?

Result Error Handling is published under the Apache-2.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Result Error Handling use?

About 4.2k tokens (SKILL.md is roughly 17k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Result Error Handling?

Skills that share tags, products or a category with Result Error Handling: Mole Bug Patterns (tw93/Mole, 70k stars), Native Data Fetching (CherryHQ/cherry-studio-app, 4k stars), Rust Best Practices (farm-fe/farm, 5.6k stars) and R Function Input Validation (tidyverse/dplyr, 5.1k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Result Error Handling?

andymai (a GitHub user) maintains it in andymai/brepjs, which has 115 GitHub stars. The repository holds 21 skills in this directory. The repository was last updated on October 8, 2026.

Source: andymai/brepjs on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.