XAMPPRocky / octocrab

A modern, extensible GitHub API Client for Rust.
Other
1.06k stars 258 forks source link

Expose status_code in GithubError #598

Closed flying-sheep closed 5 months ago

flying-sheep commented 6 months ago

I’d like to handle a 404 by matching the status code, not the error message or error vector.

XAMPPRocky commented 6 months ago

Thank you for your issue! However what advantage does that have over matching on the error kind?

flying-sheep commented 6 months ago

If that existed for GitHubError, that would be even better, but it doesn’t:

#[non_exhaustive]
pub struct GitHubError {
    pub documentation_url: Option<String>,
    pub errors: Option<Vec<Value>>,
    pub message: String,
}
flying-sheep commented 5 months ago

OK, done.

One way to use it would be something like the following.

If you want, I can something like that to the PR, but we’d have to decide on a name (e.g. should it just be impl<T> Into<octocrab::Result<Option<T>>> for octocrab::Result<T>?)

use octocrab::error::{Error, GitHubError};

pub trait OctocrabOptional<T> {
    fn found(self) -> octocrab::Result<Option<T>>;
}

impl<T> OctocrabOptional<T> for octocrab::Result<T> {
    fn found(self) -> octocrab::Result<Option<T>> {
        match self {
            Ok(commit) => Ok(Some(commit)),
            Err(Error::GitHub {
                source:
                    GitHubError {
                        status_code: http::StatusCode::NOT_FOUND,
                        ..
                    },
                ..
            }) => Ok(None),
            Err(e) => Err(e),
        }
    }
}

Then you could do things like:

let ref_: Option<Ref> = octocrab::instance()
    .repos(org, repo)
    .get_ref(&Reference::Branch("main".to_owned()))
    .await
    .found()?;