Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom error implementation #18

Open
OliverBrotchie opened this issue Jan 3, 2022 · 1 comment
Open

Custom error implementation #18

OliverBrotchie opened this issue Jan 3, 2022 · 1 comment
Labels
enhancement New feature or request good first issue Good for newcomers

Comments

@OliverBrotchie
Copy link
Owner

Custom error should be implemented to replace the boxed generic error to give better outputs.

@OliverBrotchie OliverBrotchie added the enhancement New feature or request label Jan 3, 2022
@OliverBrotchie OliverBrotchie added the good first issue Good for newcomers label Apr 11, 2022
@OliverBrotchie
Copy link
Owner Author

Example of a custom error:

#[derive(Debug)]
struct DocError {
    message: String,
    kind: ErrorKind,
}

#[derive(Debug)]
enum ErrorKind {
    IncorrectFileExtension,
    PathingError,
    GitignoreError,
    JSONConversionError,
}

impl fmt::Display for DocError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            format!("{}, Error Type: {:?}", self.message, self.kind)
        )
    }
}

impl convert::From<globset::Error> for DocError {
    fn from(error: globset::Error) -> Self {
        DocError {
            message: error.to_string(),
            kind: ErrorKind::GitignoreError,
        }
    }
}

impl convert::From<io::Error> for DocError {
    fn from(error: io::Error) -> Self {
        DocError {
            message: error.to_string(),
            kind: ErrorKind::PathingError,
        }
    }
}

impl convert::From<serde_json::Error> for DocError {
    fn from(error: serde_json::Error) -> Self {
        DocError {
            message: error.to_string(),
            kind: ErrorKind::JSONConversionError,
        }
    }
}

Which will then replace:

fn someFunction() -> Result<SomeReturnType, Box<dyn std::error::Error>>

With:

fn someFunction() -> Result<SomeReturnType, DocError> 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request good first issue Good for newcomers
Projects
None yet
Development

No branches or pull requests

1 participant