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

Integrating Library Errors

Adapt third-party error types into internal domain models efficiently.

In this lesson, you will learn how to wrap external third-party errors into your own domain-specific error types to keep your codebase clean and decoupled.

When building a Rust application, you will frequently rely on external libraries (crates). These crates will return their own unique error types (like reqwest::Error or serde_json::Error). If you leak these types into your core business logic, your entire system becomes tightly coupled to those specific libraries. If you decide to swap a library later, you would have to update every function in your project that touches those errors.

The Domain Model Strategy

Instead of exposing library errors directly, define an internal AppError enum that captures the meaning of the failure for your domain, rather than the implementation details of the tool you used.

Here is how you bridge that gap:

// Our internal domain error
pub enum AppError {
    NetworkIssue(String),
    DataFormatError(String),
}

// Suppose we are using a library that returns `serde_json::Error`
fn parse_config(data: &str) -> Result<Config, AppError> {
    serde_json::from_str(data).map_err(|e| {
        // We adapt the external error into our domain language
        AppError::DataFormatError(format!("Config parsing failed: {}", e))
    })
}

Why this works

By using .map_err(), you translate the "How" (the technical failure of a specific JSON parser) into the "What" (a data format issue relevant to your application's domain). This approach allows your business logic to remain agnostic of external dependencies. If you later replace serde_json with a different format like TOML, you only need to change the code inside your conversion logic, not the functions that consume the AppError.

This decoupling is essential for maintainable, professional-grade Rust code, ensuring that your core logic isn't cluttered with the implementation specifics of your dependencies.

Key Takeaway: Always map external library errors into your own domain-specific error types to prevent leaking technical implementation details into your application logic.