ob
ob copied to clipboard
Custom error implementation
Custom error should be implemented to replace the boxed generic error to give better outputs.
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>