Add helper trait to add context to io errors

This commit is contained in:
Félix Saparelli 2022-01-16 19:09:50 +13:00
parent c821faf383
commit b29b3bf1e0
No known key found for this signature in database
GPG Key ID: B948C4BAE44FC474
3 changed files with 39 additions and 1 deletions

View File

@ -10,3 +10,9 @@ pub use specialised::*;
mod critical;
mod runtime;
mod specialised;
/// Helper trait to construct specific IO errors from generic ones.
pub trait SpecificIoError<Output> {
/// Add some context to the error or result.
fn about(self, context: &'static str) -> Output;
}

View File

@ -4,7 +4,7 @@ use tokio::{sync::mpsc, task::JoinError};
use crate::event::Event;
use super::RuntimeError;
use super::{RuntimeError, SpecificIoError};
/// Errors which are not recoverable and stop watchexec execution.
#[derive(Debug, Diagnostic, Error)]
@ -63,3 +63,18 @@ pub enum CriticalError {
#[diagnostic(code(watchexec::critical::internal::missing_handler))]
MissingHandler,
}
impl<T> SpecificIoError<Result<T, CriticalError>> for Result<T, std::io::Error> {
fn about(self, context: &'static str) -> Result<T, CriticalError> {
self.map_err(|err| err.about(context))
}
}
impl SpecificIoError<CriticalError> for std::io::Error {
fn about(self, context: &'static str) -> CriticalError {
CriticalError::IoError {
about: context,
err: self,
}
}
}

View File

@ -6,6 +6,8 @@ use tokio::sync::mpsc;
use crate::{event::Event, fs::Watcher, signal::process::SubSignal};
use super::SpecificIoError;
/// Errors which _may_ be recoverable, transient, or only affect a part of the operation, and should
/// be reported to the user and/or acted upon programatically, but will not outright stop watchexec.
#[derive(Debug, Diagnostic, Error)]
@ -225,3 +227,18 @@ pub enum RuntimeError {
#[diagnostic(code(watchexec::runtime::set))]
Set(#[related] Vec<RuntimeError>),
}
impl<T> SpecificIoError<Result<T, RuntimeError>> for Result<T, std::io::Error> {
fn about(self, context: &'static str) -> Result<T, RuntimeError> {
self.map_err(|err| err.about(context))
}
}
impl SpecificIoError<RuntimeError> for std::io::Error {
fn about(self, context: &'static str) -> RuntimeError {
RuntimeError::IoError {
about: context,
err: self,
}
}
}