XAMPPRocky/octocrab

Expose status_code in GithubError

Closed this issue · 3 comments

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

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

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,
}

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()?;