error-conversion-guide
Guides users on error conversion patterns, From trait implementations, and the ? operator. Activates when users need to convert between error types or handle multiple error types in a function.
What this skill does
# Error Conversion Guide Skill
You are an expert at Rust error conversion patterns. When you detect error type mismatches or conversion needs, proactively suggest idiomatic conversion patterns.
## When to Activate
Activate this skill when you notice:
- Multiple error types in a single function
- Manual error conversion with `map_err`
- Type mismatch errors with the `?` operator
- Questions about From/Into traits for errors
- Need to combine different error types
## Error Conversion Patterns
### Pattern 1: Automatic Conversion with #[from]
**What to Look For**:
- Manual `map_err` calls that could be automatic
- Repetitive error conversions
**Before**:
```rust
#[derive(Debug)]
pub enum AppError {
Io(std::io::Error),
Parse(std::num::ParseIntError),
}
fn process() -> Result<i32, AppError> {
let content = std::fs::read_to_string("data.txt")
.map_err(|e| AppError::Io(e))?; // ❌ Manual conversion
let num = content.trim().parse::<i32>()
.map_err(|e| AppError::Parse(e))?; // ❌ Manual conversion
Ok(num)
}
```
**After**:
```rust
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("IO error")]
Io(#[from] std::io::Error), // ✅ Automatic From impl
#[error("Parse error")]
Parse(#[from] std::num::ParseIntError), // ✅ Automatic From impl
}
fn process() -> Result<i32, AppError> {
let content = std::fs::read_to_string("data.txt")?; // ✅ Auto-converts
let num = content.trim().parse::<i32>()?; // ✅ Auto-converts
Ok(num)
}
```
**Suggestion Template**:
```
Use #[from] in your error enum to enable automatic conversion:
#[derive(Error, Debug)]
pub enum AppError {
#[error("IO error")]
Io(#[from] std::io::Error),
}
This implements From<std::io::Error> for AppError, allowing ? to automatically convert.
```
### Pattern 2: Manual From Implementation
**What to Look For**:
- Custom error types that need conversion
- Complex conversion logic
**Pattern**:
```rust
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("Database error: {message}")]
Database { message: String },
#[error("Validation error: {0}")]
Validation(String),
}
// Manual From for custom conversion logic
impl From<sqlx::Error> for AppError {
fn from(err: sqlx::Error) -> Self {
AppError::Database {
message: format!("Database operation failed: {}", err),
}
}
}
// Convert with context
impl From<validator::ValidationErrors> for AppError {
fn from(err: validator::ValidationErrors) -> Self {
let messages: Vec<String> = err
.field_errors()
.iter()
.map(|(field, errors)| {
format!("{}: {:?}", field, errors)
})
.collect();
AppError::Validation(messages.join(", "))
}
}
```
**Suggestion Template**:
```
When you need custom conversion logic, implement From manually:
impl From<SourceError> for AppError {
fn from(err: SourceError) -> Self {
AppError::Variant {
field: extract_info(&err),
}
}
}
```
### Pattern 3: Converting Between Result Types
**What to Look For**:
- Calling functions with different error types
- Need to unify error types
**Pattern**:
```rust
use thiserror::Error;
#[derive(Error, Debug)]
pub enum ServiceError {
#[error("Repository error")]
Repository(#[from] RepositoryError),
#[error("External API error")]
Api(#[from] ApiError),
#[error("Validation error")]
Validation(#[from] ValidationError),
}
// All these errors convert automatically
fn service_operation() -> Result<Data, ServiceError> {
// Returns Result<_, RepositoryError>
let data = repository.fetch()?; // ✅ Auto-converts to ServiceError
// Returns Result<_, ValidationError>
validate(&data)?; // ✅ Auto-converts to ServiceError
// Returns Result<_, ApiError>
let enriched = api_client.enrich(data)?; // ✅ Auto-converts to ServiceError
Ok(enriched)
}
```
**Suggestion Template**:
```
Create a unified error type that can convert from all the errors you need:
#[derive(Error, Debug)]
pub enum UnifiedError {
#[error("Database error")]
Database(#[from] DbError),
#[error("Network error")]
Network(#[from] NetworkError),
}
fn operation() -> Result<(), UnifiedError> {
db_operation()?; // Auto-converts
network_operation()?; // Auto-converts
Ok(())
}
```
### Pattern 4: map_err for One-Off Conversions
**What to Look For**:
- Single conversion that doesn't justify From impl
- Adding context during conversion
**Pattern**:
```rust
use anyhow::Context;
fn process(id: &str) -> anyhow::Result<Data> {
// One-off conversion with context
let config = load_config()
.map_err(|e| anyhow::anyhow!("Failed to load config: {}", e))?;
// Better: use context
let config = load_config()
.context("Failed to load config")?;
// map_err for type conversion without From impl
let data = fetch_data(id)
.map_err(|e| format!("Fetch failed for {}: {}", id, e))?;
Ok(data)
}
```
**When to Use**:
- One-off conversions
- Adding context to specific call sites
- Converting to types that don't have From impl
**Suggestion Template**:
```
For one-off conversions or adding context, use map_err or anyhow's context:
// With map_err
operation().map_err(|e| MyError::Custom(format!("Failed: {}", e)))?;
// With anyhow (preferred)
operation().context("Operation failed")?;
```
### Pattern 5: Error Type Aliases
**What to Look For**:
- Repetitive Result<T, MyError> types
- Complex error type signatures
**Pattern**:
```rust
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("IO error")]
Io(#[from] std::io::Error),
#[error("Parse error")]
Parse(#[from] serde_json::Error),
}
// Type alias for cleaner signatures
pub type Result<T> = std::result::Result<T, AppError>;
// Now use it everywhere
pub fn load_config() -> Result<Config> { // ✅ Clean
let bytes = std::fs::read("config.json")?;
let config = serde_json::from_slice(&bytes)?;
Ok(config)
}
// Instead of
pub fn load_config_verbose() -> std::result::Result<Config, AppError> { // ❌ Verbose
// ...
}
```
**Suggestion Template**:
```
Create a type alias for your Result type:
pub type Result<T> = std::result::Result<T, AppError>;
Then use it in function signatures:
pub fn operation() -> Result<Data> {
Ok(data)
}
```
### Pattern 6: Boxing Errors
**What to Look For**:
- Need for dynamic error types
- Functions that can return multiple error types
**Pattern**:
```rust
// For libraries that need flexibility
type BoxError = Box<dyn std::error::Error + Send + Sync>;
fn flexible_function() -> Result<Data, BoxError> {
let data1 = io_operation()?; // std::io::Error auto-boxes
let data2 = parse_operation()?; // ParseError auto-boxes
Ok(combine(data1, data2))
}
// Or use anyhow for applications
use anyhow::Result;
fn application_function() -> Result<Data> {
let data1 = io_operation()?;
let data2 = parse_operation()?;
Ok(combine(data1, data2))
}
```
**Trade-offs**:
- ✅ Flexible: Can return any error type
- ✅ Simple: No need to define custom error enum
- ❌ Dynamic: Error type not known at compile time
- ❌ Harder to match on specific errors
**Suggestion Template**:
```
For flexible error handling, use Box<dyn Error> or anyhow:
// Libraries: Box<dyn Error>
type BoxError = Box<dyn std::error::Error + Send + Sync>;
fn operation() -> Result<T, BoxError> { ... }
// Applications: anyhow
use anyhow::Result;
fn operation() -> Result<T> { ... }
```
### Pattern 7: Layered Error Conversion
**What to Look For**:
- Multi-layer architecture (domain, infra, app)
- Need for error boundary between layers
**Pattern**:
```rust
use thiserror::Error;
// Infrastructure layer
#[derive(Error, Debug)]
pub enum InfraError {
#[error("Database error")]
Database(#[from] sqlx::Error),
#[error("HTTP error")]
Related in Ads & Marketing
ads
IncludedMulti-platform paid advertising audit and optimization skill. Analyzes Google, Meta, YouTube, LinkedIn, TikTok, Microsoft, and Apple Ads. 250+ checks with scoring, parallel agents, industry templates, and AI creative generation.
banana
IncludedAI image generation Creative Director powered by Google Gemini Nano Banana models. Use this skill for ANY request involving image creation, editing, visual asset production, or creative direction. Triggers on: generate an image, create a photo, edit this picture, design a logo, make a banner, visual for my anything, and all /banana commands. Handles text-to-image, image editing, multi-turn creative sessions, batch workflows, and brand presets.
rpg-migration-analyzer
IncludedAnalyzes legacy RPG (Report Program Generator) programs from AS/400 and IBM i systems for migration to modern Java applications. Extracts business logic from RPG III/IV/ILE source code, identifies data structures (D-specs), file operations (F-specs), program dependencies (CALLB/CALLP), and converts RPG constructs to Java equivalents. Generates migration reports, complexity estimates, and Java implementation strategies with POJO classes, JPA entities, and service methods. Use when modernizing AS/400 or IBM i legacy systems, analyzing RPG source files (.rpg, .rpgle, .RPGLE), converting RPG to Java, mapping data specifications to Java classes, planning legacy system migration, or when user mentions RPG analysis, Report Program Generator, RPG III/IV/ILE, AS/400 modernization, IBM i migration, packed decimal conversion, or mainframe application rewrite.
brand-library-architect
IncludedBuild a complete brand library for a product — visual asset render pipeline, brand documentation set (BRAND, COPY, MANIFESTO, BIOS, FAQ, GLOSSARY, TONE, PRICING), open-source convention files (README, CONTRIBUTING, SECURITY, CODE_OF_CONDUCT), and a self-contained press kit. This skill should be used when the user asks to "build a brand library / brand kit / press kit / brand assets" for a product, "set up a brand library workflow," "create a positioning manifesto plus visual identity," or any combination of brand documentation + visual asset pipeline. Apply phase-by-phase or run end-to-end. Templates are product-agnostic and use {{TOKEN}} placeholders the skill prompts the user to fill.
writing-tech-post
IncludedAuthors engineering blog posts end-to-end: launch deep-dives, incident postmortems, architecture migrations, performance case studies, tutorials, AI/agent system writeups, security disclosures, and research-to-product translations. Picks the correct archetype, plans the abstraction ladder, enforces an evidence cadence (diagrams, benchmarks, profiles, traces, code, ablations), tunes voice against publisher house styles (Datadog, Vercel, GitHub, AWS, Meta, Cloudflare, Jane Street), and runs a pre-publish gate for narrative momentum and disclosure ethics. Use when drafting a new engineering post, restructuring a draft that feels flat, deciding which evidence form belongs where, validating that depth and product context are balanced, or preparing a postmortem, migration, or performance narrative for external publication. Do not use for API reference documentation, README authoring, marketing copy, release notes, generic SEO content, ghost-written executive thought leadership, or non-engineering long-form essays.
blog-google
IncludedGoogle API integration for blog performance: PageSpeed Insights, CrUX Core Web Vitals with 25-week history, Search Console performance, URL Inspection, Indexing API, GA4 organic traffic, NLP entity analysis for E-E-A-T, YouTube video search for embedding, and Google Ads Keyword Planner. Progressive feature availability based on credential tier (API key, OAuth/service account, GA4, Ads). Shares config with claude-seo at ~/.config/claude-seo/google-api.json. Use when user says "google data", "page speed", "core web vitals", "search console", "indexation", "GA4", "keyword research", "nlp entities", "blog performance", "youtube search", "google api setup".