ob icon indicating copy to clipboard operation
ob copied to clipboard

Custom error implementation

Open OliverBrotchie opened this issue 4 years ago • 1 comments

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

OliverBrotchie avatar Jan 03 '22 22:01 OliverBrotchie

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> 

OliverBrotchie avatar Apr 11 '22 10:04 OliverBrotchie