Idiomatic Rust error handling: Result and ?, typed errors with thiserror in libraries, anyhow with context in applications, and documented error conditions.
.cursor/rules/rust-error-handling.mdc. Downloaded files need to be placed in that repository path.---
description: "Idiomatic Rust error handling: Result and ?, typed errors with thiserror in libraries, anyhow with context in applications, and documented error conditions."
globs: "**/*"
alwaysApply: false
---
Apply these rules when handling errors in Rust.
## Result, Option and ?
- Return `Result<T, E>` from any operation that can fail for reasons the caller should handle; use `Option<T>` only when absence is a normal, unexplained outcome.
- Propagate with `?`. Convert an `Option` to a `Result` with `ok_or` / `ok_or_else` when the absence is an error the caller needs to see.
- Do not `unwrap()` in library or request-handling code. Use `expect("reason this cannot fail")` only for real invariants, and keep `unwrap()` to tests and examples.
- Reserve `panic!` for bugs (broken invariants), not for invalid input or I/O failures.
## Libraries: typed errors
- Define an error enum per library or module boundary, with variants the caller can match on. Derive `Display` and `Error` with `thiserror`, and use `#[from]` to generate `From` impls so `?` converts source errors.
- Keep the underlying error as a `source` instead of formatting it into a string.
```rust
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("could not read config file {path}")]
Read { path: String, #[source] source: std::io::Error },
#[error("invalid config")]
Parse(#[from] toml::de::Error),
#[error("missing required key `{0}`")]
MissingKey(&'static str),
}
```
## Applications: context
- In binaries, use `anyhow::Result` (or `eyre`) and add context at each layer with `.context(...)` / `.with_context(|| ...)` so the final report explains what was being attempted.
- Return `anyhow::Result<()>` from `main` or handle the error at the top level and set a non-zero exit code.
## Documentation
- Document error conditions of public functions in a `# Errors` section (Clippy's `missing_errors_doc` lint checks this), and panics in a `# Panics` section.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
language
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A CLI's config loader uses unwrap() on file reads and returns Result<Config, String>, so callers cannot tell a missing file from a parse error.
Apply the Rust Error Handling rule to src/config.rs (library crate used by the CLI binary in src/main.rs).
A thiserror enum with Read (keeping the io::Error as source), Parse (#[from] toml error) and MissingKey variants; ? propagation instead of unwrap; main.rs using anyhow with .context("loading config from ..."); a # Errors doc section on the public load function.Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/rust-error-handling.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Rust Error Handling project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these rules when handling errors in Rust.
## Result, Option and ?
- Return `Result<T, E>` from any operation that can fail for reasons the caller should handle; use `Option<T>` only when absence is a normal, unexplained outcome.
- Propagate with `?`. Convert an `Option` to a `Result` with `ok_or` / `ok_or_else` when the absence is an error the caller needs to see.
- Do not `unwrap()` in library or request-handling code. Use `expect("reason this cannot fail")` only for real invariants, and keep `unwrap()` to tests and examples.
- Reserve `panic!` for bugs (broken invariants), not for invalid input or I/O failures.
## Libraries: typed errors
- Define an error enum per library or module boundary, with variants the caller can match on. Derive `Display` and `Error` with `thiserror`, and use `#[from]` to generate `From` impls so `?` converts source errors.
- Keep the underlying error as a `source` instead of formatting it into a string.
```rust
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("could not read config file {path}")]
Read { path: String, #[source] source: std::io::Error },
#[error("invalid config")]
Parse(#[from] toml::de::Error),
#[error("missing required key `{0}`")]
MissingKey(&'static str),
}
```
## Applications: context
- In binaries, use `anyhow::Result` (or `eyre`) and add context at each layer with `.context(...)` / `.with_context(|| ...)` so the final report explains what was being attempted.
- Return `anyhow::Result<()>` from `main` or handle the error at the top level and set a non-zero exit code.
## Documentation
- Document error conditions of public functions in a `# Errors` section (Clippy's `missing_errors_doc` lint checks this), and panics in a `# Panics` section.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.