Skip to content

code-yeongyu/oh-my-openagent / packages/shared-skills/skills/programming

programming

Unverified

Applies strict, modern language practice (typed errors, exhaustive match, tests that can fail) for Python, Rust, TypeScript, JavaScript, and Go. Use for work on .py, .rs, .ts, .js, or .go files, and whenever a test or spec file is written, reshaped, reviewed, or deleted: the four-question test authoring gate and the junk-test classes live here.

FileKindSize
SKILL.mdskill md33.3 KB
references/code-smells.mdmarkdown13.9 KB
references/go/README.mdmarkdown7.7 KB
references/go/backend-stack.mdmarkdown16.6 KB
references/go/bootstrap.mdmarkdown8.9 KB
references/go/bubbletea-v2.mdmarkdown11.3 KB
references/go/cobra-stack.mdmarkdown11.5 KB
references/go/concurrency.mdmarkdown10.9 KB
references/go/data-modeling.mdmarkdown12.0 KB
references/go/error-handling.mdmarkdown10.1 KB
references/go/golangci-strict.mdmarkdown10.0 KB
references/go/grpc-connect.mdmarkdown10.3 KB
references/go/libraries.mdmarkdown13.7 KB
references/go/one-liners.mdmarkdown5.5 KB
references/go/sqlc-pgx.mdmarkdown12.7 KB
references/go/testing.mdmarkdown14.2 KB
references/go/type-patterns.mdmarkdown9.5 KB
references/logging.mdmarkdown10.5 KB
references/python/README.mdmarkdown15.7 KB
references/python/async-anyio.mdmarkdown14.2 KB
references/python/data-modeling.mdmarkdown6.6 KB
references/python/data-processing.mdmarkdown4.2 KB
references/python/error-handling.mdmarkdown6.0 KB
references/python/fastapi-stack.mdmarkdown9.2 KB
references/python/httpx2-optimization.mdmarkdown12.0 KB
references/python/libraries.mdmarkdown10.6 KB
references/python/one-liners.mdmarkdown7.9 KB
references/python/orjson-stack.mdmarkdown13.3 KB
references/python/pydantic-ai.mdmarkdown8.2 KB
references/python/pyproject-strict.mdmarkdown9.0 KB
references/python/textual-tui.mdmarkdown5.1 KB
references/python/type-patterns.mdmarkdown4.1 KB
references/rust-ub/README.mdmarkdown9.9 KB
references/rust-ub/miri-sanitizers-loom.mdmarkdown11.5 KB
references/rust-ub/ub-taxonomy.mdmarkdown13.3 KB
references/rust/README.mdmarkdown16.6 KB
references/rust/api-design.mdmarkdown6.5 KB
references/rust/async-tokio.mdmarkdown12.6 KB
references/rust/axum-stack.mdmarkdown14.2 KB
references/rust/cargo-strict.mdmarkdown10.0 KB
references/rust/clap-stack.mdmarkdown12.1 KB
references/rust/concurrency.mdmarkdown14.3 KB
references/rust/libraries.mdmarkdown17.4 KB
references/rust/macros.mdmarkdown3.3 KB
references/rust/one-liners.mdmarkdown7.5 KB
references/rust/proptest-insta.mdmarkdown13.9 KB
references/rust/type-state.mdmarkdown13.1 KB
references/rust/unsafe-discipline.mdmarkdown12.9 KB
references/rust/zero-cost-safety.mdmarkdown16.9 KB
references/testing/README.mdmarkdown10.3 KB
references/testing/junk-classes.mdmarkdown6.2 KB
references/typescript/README.mdmarkdown10.6 KB
references/typescript/backend-hono.mdmarkdown21.2 KB
references/typescript/bootstrap.mdmarkdown6.9 KB
references/typescript/data-modeling.mdmarkdown5.0 KB
references/typescript/error-handling.mdmarkdown4.7 KB
references/typescript/oxc-lint.mdmarkdown7.6 KB
references/typescript/tsconfig-strict.mdmarkdown3.9 KB
references/typescript/type-patterns.mdmarkdown5.2 KB
scripts/go/check-no-excuse-rules.shexecutablescript7.1 KB
scripts/go/new-project.tsscript6.8 KB
scripts/go/templates/.editorconfigother206 B
scripts/go/templates/.golangci.ymlconfig1.5 KB
scripts/go/templates/AGENTS.md.tmplother845 B
scripts/go/templates/README.md.tmplother207 B
scripts/go/templates/Taskfile.ymlconfig706 B
scripts/go/templates/ci.ymlconfig863 B
scripts/go/templates/config.goscript643 B
scripts/go/templates/gitignoreother99 B
scripts/go/templates/main.go.tmplother329 B
scripts/go/templates/run.goscript350 B
scripts/python/check-no-excuse-rules.pyscript24.9 KB
scripts/python/new-project.tsscript6.7 KB
scripts/python/new-script.tsscript4.2 KB
scripts/rust/check-no-excuse-rules.shexecutablescript7.5 KB
scripts/rust/check-no-excuse-rules.test.tsscript3.4 KB
scripts/rust/new-project.tsscript6.1 KB
scripts/scaffolders.test.tsscript4.9 KB
scripts/shared/run-tool.tsscript855 B
scripts/typescript/check-no-excuse-rules.test.tsscript4.0 KB
scripts/typescript/check-no-excuse-rules.tsscript13.1 KB
scripts/typescript/check-test-junk-rules.tsscript5.5 KB
scripts/typescript/check-test-junk.test.tsscript4.9 KB
scripts/typescript/check-test-junk.tsscript5.4 KB
scripts/typescript/mutation-proof.test.tsscript1.9 KB
scripts/typescript/mutation-proof.tsscript6.4 KB
scripts/typescript/new-project.test.tsscript6.8 KB
scripts/typescript/new-project.tsscript3.1 KB
scripts/typescript/oxc/.oxfmtrc.jsonconfig256 B
scripts/typescript/oxc/.oxlintrc.jsonconfig1.7 KB
scripts/typescript/oxc/lint/oxlint-plugin/LICENSEother1.0 KB
scripts/typescript/oxc/lint/oxlint-plugin/index.jsscript288 B
scripts/typescript/oxc/lint/oxlint-plugin/no-em-dash-copy.jsscript785 B
scripts/typescript/oxc/lint/oxlint-plugin/require-suppression-reason.jsscript2.3 KB
scripts/typescript/oxc/tsconfig.jsonconfig794 B

references/python/error-handling.md

View on GitHub
# Error Handling

Typed errors, exhaustive matching, union returns, and resource safety.

---

## Typed errors — no bare strings

Error types carry structured data. Pattern matching works. Callers know exactly what can go wrong.

```python
from dataclasses import dataclass
from typing import NewType

UserId = NewType("UserId", int)

@dataclass(frozen=True, slots=True)
class UserNotFoundError(Exception):
    user_id: UserId

    def __str__(self) -> str:  # REQUIRED — see note below
        return f"user {self.user_id} not found"

@dataclass(frozen=True, slots=True)
class PermissionDeniedError(Exception):
    user_id: UserId
    required_role: str

    def __str__(self) -> str:
        return f"user {self.user_id} needs role {self.required_role}"
```

**`__str__` is mandatory** on dataclass exceptions. `@dataclass` replaces `Exception.__init__`, so `self.args` is always `()`. Without `__str__`, `str(e)` returns an empty string and logging/monitoring breaks.

```python
# BAD
raise ValueError("user not found")
raise ValueError("permission denied")

# GOOD
raise UserNotFoundError(user_id=uid)
raise PermissionDeniedError(user_id=uid, required_role="admin")
```

---

## Union returns — expected failures without exceptions

For failures that are **expected** (not found, validation error, permission denied), return a union instead of raising. Exceptions are for **unexpected** failures (network down, OOM, corrupted data).

### Define the outcome types

```python
@dataclass(frozen=True, slots=True)
class User:
    id: UserId
    name: str

@dataclass(frozen=True, slots=True)
class UserNotFound:
    id: UserId

@dataclass(frozen=True, slots=True)
class PermissionDenied:
    id: UserId
    reason: str

type GetUserResult = User | UserNotFound | PermissionDenied
```

### Handle exhaustively

```python
from typing import assert_never

def handle_result(result: GetUserResult) -> str:
    match result:
        case User(name=name):
            return f"Found: {name}"
        case UserNotFound(id=uid):
            return f"No user with id {uid}"
        case PermissionDenied(reason=reason):
            return f"Denied: {reason}"
        case _ as unreachable:
            assert_never(unreachable)
```

`assert_never` in the default case: if you add a new variant to `GetUserResult` without handling it here, the type checker errors. No silent fall-through.

### When to use which

**The heuristic**: caller is 1-2 levels away and MUST handle it → union return. Error should propagate up many layers to a boundary → exception.

| Scenario | Pattern | Why |
|---|---|---|
| Repository → service (caller handles it) | Union return (`User \| UserNotFound`) | Caller is right there, must handle both |
| Validation at boundary (parsing input) | Exception (typed, with fields) | Propagates up to HTTP/CLI handler |
| Infrastructure failure (network, OOM) | Exception | Can't handle locally, must propagate |
| Service → service (deep internal) | Exception (typed) | Union boilerplate across many layers is worse than exceptions |
| HTTP handler → response | Catch exceptions, convert to response | Boundary code catches and translates |

**Practical tradeoff**: union returns are safest (type checker forces handling) but create boilerplate when every caller in a chain must `match`. If the error would just propagate through 3+ layers unchanged, use a typed exception instead.

---

## Exhaustive match — every match needs a default

Every `match` statement ends with `case _: assert_never(x)`. No exceptions.

```python
from enum import StrEnum
from typing import assert_never

class Status(StrEnum):
    PENDING = "pending"
    ACTIVE = "active"
    DELETED = "deleted"

def describe(status: Status) -> str:
    match status:
        case Status.PENDING:
            return "waiting"
        case Status.ACTIVE:
            return "live"
        case Status.DELETED:
            return "gone"
        case _ as unreachable:
            assert_never(unreachable)
```

Add a new enum member? The type checker tells you every `match` that needs updating.

---

## Context managers — resource safety

If it has `.close()`, `.shutdown()`, `.disconnect()`, or `.release()`, wrap it in `with`.

```python
# BAD
f = open("data.txt")
data = f.read()
f.close()  # forgotten? leaked

# GOOD
from pathlib import Path

data = Path("data.txt").read_text()
```

### Async resources

```python
import httpx

async def fetch_users() -> list[User]:
    async with httpx.AsyncClient() as client:
        response = await client.get("https://api.example.com/users")
        response.raise_for_status()
        return [User(**u) for u in response.json()]
```

### Custom context manager

```python
from contextlib import asynccontextmanager
from collections.abc import AsyncIterator

@asynccontextmanager
async def managed_connection(url: str) -> AsyncIterator[Connection]:
    conn = await connect(url)
    try:
        yield conn
    finally:
        await conn.close()

async with managed_connection("postgres://...") as conn:
    await conn.execute("SELECT 1")
# conn is closed here, guaranteed
```

---

## Exception hierarchy — when you do raise

Keep exception hierarchies shallow and specific.

```python
class AppError(Exception):
    """Base for all application errors."""

@dataclass(frozen=True, slots=True)
class NotFoundError(AppError):
    entity: str
    id: int

    def __str__(self) -> str:
        return f"{self.entity} {self.id} not found"

@dataclass(frozen=True, slots=True)
class ConflictError(AppError):
    entity: str
    field: str
    value: str

    def __str__(self) -> str:
        return f"{self.entity}.{self.field} = {self.value!r} already exists"
```

Callers catch `AppError` at the boundary, or specific subtypes where they can do something useful.

---

## Sources

- Python docs: [typing — assert_never](https://docs.python.org/3/library/typing.html#typing.assert_never)
- Python docs: [contextlib](https://docs.python.org/3/library/contextlib.html)
- Python docs: [match statement](https://docs.python.org/3/reference/compound_stmts.html#the-match-statement)
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 318kUpdated Claude CodeCodexUnverifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 318kUpdated Claude CodeCodexUnverifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 318kUpdated Claude CodeCodexUnverifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 196kUpdated Claude CodeCodexVerifiedInstall