Hasty Briefsbeta

Bilingual

Designing Error Types in Rust Libraries

a year ago
  • #Error Handling
  • #Rust
  • #Library Design
  • Designing error types in Rust libraries requires careful consideration, especially for public APIs.
  • Binary crates often use crates like anyhow or eyre for error handling, focusing on user messages.
  • Library crates need to design error types carefully as they become part of the public API.
  • Two main approaches for library error types: using thiserror crate or a custom error type similar to std::io::Error.
  • thiserror reduces boilerplate and allows converting other error types into custom errors using #[from].
  • Avoid leaking inner error types (e.g., sqlx::Error) to prevent unnecessary dependencies for library users.
  • Solution: Use Box<dyn std::error::Error + Send + Sync> to encapsulate inner errors and maintain API flexibility.
  • std::io::Error serves as a good reference with its ErrorKind enum and opaque error handling.
  • Key features of std::io::Error include non-exhaustive enums, boxed trait objects, and clean public API design.
  • Choose between thiserror with boxing or custom error types based on library use case and public API needs.