How to handle custom errors after description deprecation

Provided code that works but throws deprecation warnings:

#[derive(Debug)]
pub enum ApiClientError {
    HTTPRequestError(String),
}

impl Error for ApiClientError {
    fn description(&self) -> &str {
        match *self {
            APIClientError::HTTPRequestError(ref cause) => cause,
        }
    }
}

impl From<reqwest::Error> for ApiClientError {
    fn from(err: reqwest::Error) -> APIClientError {
        APIClientError::HTTPRequestError(err.source().unwrap().to_string())
    }
}

impl fmt::Display for ApiClientError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

Usage example:

let api_client = match ApiClient::new() {
        Ok(c) => c,
        Err(err) => {
            error!("{}", err);
            exit(1)
        }
    };

However, if I remove description implementation from impl Error for ApiClientError, and try to use to_string on errors instead, error! throws memory stack overflow.

How to properly handle custom error type such as ApiClientError?

Typically this is how custom errors are built:

#[derive(Debug)]
pub enum ApiClientError {
    HTTPRequestError(reqwest::Error),
}

impl Error for ApiClientError {}

impl From<reqwest::Error> for ApiClientError {
    fn from(err: reqwest::Error) -> APIClientError {
        APIClientError::HTTPRequestError(err)
    }
}

impl fmt::Display for ApiClientError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            APIClientError::HTTPRequestError(ref err) => err.fmt(f),
        }
    }
}

Excellent! Thank you so much :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.