Course contentsShow
← Rust
Lesson 833 of 1,9107. Error Handling PatternsFree lesson

Extending Errors with Metadata

Add fields to error types to carry diagnostic information alongside failure codes.

In this lesson, you will learn how to enrich your custom error types with structured diagnostic data to make debugging significantly more efficient.

Moving Beyond Simple Error Codes

Up until now, you have likely represented errors as simple enums (e.g., enum FileError { NotFound, PermissionDenied }). While these are perfect for branching logic, they are often insufficient for complex applications where you need to know what went wrong and why.

By "extending errors with metadata," we transition from treating errors as mere labels to treating them as containers for context. Instead of just knowing a file wasn't found, you can include the specific file path or even the timestamp of the failure.

Structuring Your Error Types

You can transform your variants from simple tags into structs that hold specific fields. Consider this transition:

// Simple approach
enum ConfigError {
    MissingKey,
}

// Metadata-enriched approach
enum ConfigError {
    MissingKey { 
        key_name: String, 
        line_number: usize 
    },
}

By storing key_name and line_number, you no longer have to guess what caused the program to crash. When you handle this error, you gain access to these fields through pattern matching:

match error {
    ConfigError::MissingKey { key_name, line_number } => {
        println!("Error: '{}' not found on line {}", key_name, line_number);
    }
}

Why This Matters

Adding metadata shifts the burden of investigation from the user (who might be staring at a generic "File Not Found" message) to your code. When you provide this extra information, you allow the calling code to potentially perform more granular recovery operations—such as prompting the user to check a specific line in a configuration file—rather than just aborting the entire process.

By bundling diagnostic information directly into your error variants, you create a self-documenting failure path that is much easier to maintain as your project grows in complexity.

Key Takeaway: Enhance your error variants by adding fields to store diagnostic metadata, transforming vague failures into actionable intelligence.