Skip to content

Commit

Permalink
feat(utils): various convenience utilities for creating and working w…
Browse files Browse the repository at this point in the history
…ith Diagnostics
  • Loading branch information
zkat committed Aug 14, 2021
1 parent fd0d2b1 commit a960136
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
pub use error::*;
pub use protocol::*;
pub use reporter::*;
pub use utils::*;

mod chain;
mod error;
mod protocol;
mod reporter;
mod source_impls;
mod utils;
39 changes: 39 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use std::fmt;

use thiserror::Error;

use crate::Diagnostic;

/// Convenience [Diagnostic] that can be used as an "anonymous" wrapper for
/// Errors. This is intended to be paired with [IntoDiagnostic].
#[derive(Debug, Error)]
#[error("{}", self.error)]
pub struct DiagnosticError {
#[source]
pub error: Box<dyn std::error::Error + Send + Sync + 'static>,
pub code: String,
}

impl Diagnostic for DiagnosticError {
fn code<'a>(&'a self) -> Box<dyn std::fmt::Display + 'a> {
Box::new(&self.code)
}
}

/// Utility Result type for functions that return boxed [Diagnostic]s.
pub type DiagnosticResult<T> = Result<T, Box<dyn Diagnostic + Send + Sync + 'static>>;

pub trait IntoDiagnostic<T, E> {
/// Converts [Result]-like types that return regular errors into a
/// `Result` that returns a [Diagnostic].
fn into_diagnostic(self, code: &(dyn fmt::Display)) -> Result<T, DiagnosticError>;
}

impl<T, E: std::error::Error + Send + Sync + 'static> IntoDiagnostic<T, E> for Result<T, E> {
fn into_diagnostic(self, code: &(dyn fmt::Display)) -> Result<T, DiagnosticError> {
self.map_err(|e| DiagnosticError {
error: Box::new(e),
code: format!("{}", code),
})
}
}

0 comments on commit a960136

Please sign in to comment.