Designing Error Types in Rust Libraries
d34dl0ck.me
d34dl0ck.me
public struct SqlError(sqlx::Error)
#[derive(Debug, thiserror::Error)]
pub enum MyError {
#[error("Database error: {0}")]
DatabaseError(#[from] SqlError)
}
It’s a bit more annoying to construct since result has to have a .map_error(SqlError) but that’s not that much honestly.Regarding Solution 2, you can also use thiserror on the "custom built wrapper types", which eliminates the need to manually create the From implementations.
use thiserror::Error;
#[derive(Error, Debug)]
#[error(transparent)]
pub struct DbError(sqlx::Error);
#[derive(Error, Debug)]
#[error(transparent)]
pub struct HttpError(reqwest::Error);
#[derive(Error, Debug)]
pub enum MyPublicError {
#[error("database error: {0}")]
DbError(#[from] DbError),
#[error("http error: {0}")]
HttpError(#[from] HttpError),
}
fn main() -> Result<(), MyPublicError> {
do_db_stuff()?;
Ok(())
}
fn do_db_stuff() -> Result<(), DbError> {
todo!()
}