I am learning Rust
and I would like to know what is the idiomatic way of writing a function that could run into multiple error types. For instance, in the function get_account_with_creds
I am trying to return a struct AccountForResponse
if the credentials match. The function could possibly run into a database error, so the Result
could be a PoolError
. I am using unwrap
a few places because the error types are different. How can I improve this? I am also not sure about returning Ok(None)
pub async fn get_account_with_creds(db: &Db, creds: AccountForLogin) -> Result<Option<AccountForResponse>, PoolError> {
let client: Client = db.get().await?;
let stmt = client
.prepare("SELECT id, first_name, last_name, email, password from accounts WHERE email = $1")
.await?;
let rows = client.query(&stmt, &[&creds.email]).await?;
let row = rows.first().unwrap();
let hashed_password: &str = row.get(4);
match bcrypt::verify(creds.password, hashed_password).unwrap() {
false => Ok(None),
true => {
let account = Some(AccountForResponse {
id: Some(row.get(0)),
first_name: row.get(1),
last_name: row.get(2),
email: row.get(3),
});
Ok(account)
}
}
}
anyhow
the idiomatic way of handling returning multiple error types in Rust? I intend to use it everywhere I face this issue \$\endgroup\$