TIL

Custom errors in rust

02.04.2024

On my journey to learn rust I have stumbled on the mismatch error type when using the question mark operator. I recently learned that a nice way to handle that is to have custom errors and implement the From trait for each of the errors that we need to handle. The question mark operator calls from implicitly.

In one of my side projects I have a function that fetches a RSS feed and then stores the items from the feed in a database with sqlx. To use the question mark operator in that function with all the results it gets from different libraries I use a FetchError. The possible errors in the function is sqlx::Error, reqwest::Error and feed_rs::parser::ParseFeedError.

use std::{error::Error, fmt::Display};
use feed_rs::parser::ParseFeedError;
#[derive(Debug, Clone)]
pub struct FetchError {
pub message: String,
}
impl Display for FetchError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
impl Error for FetchError {}
impl From<reqwest::Error> for FetchError {
fn from(err: reqwest::Error) -> Self {
FetchError { message: err.to_string() }
}
}
impl From<sqlx::Error> for FetchError {
fn from(err: sqlx::Error) -> Self {
FetchError { message: err.to_string() }
}
}
impl From<ParseFeedError> for FetchError {
fn from(err: ParseFeedError) -> Self {
FetchError { message: err.to_string() }
}
}