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

Allow conversion from ColoredString to Error #86

Merged
merged 1 commit into from
Dec 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions examples/as_error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
extern crate colored;

use colored::Colorize;
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
Err("ERROR".red())?
}
24 changes: 24 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
use super::ColoredString;
use std::{error::Error, fmt};

pub struct ColoredStringError(pub ColoredString);
spenserblack marked this conversation as resolved.
Show resolved Hide resolved

impl ColoredStringError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0.to_string())
}
}

impl fmt::Display for ColoredStringError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.fmt(f)
}
}

impl fmt::Debug for ColoredStringError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.fmt(f)
}
}

impl Error for ColoredStringError {}
9 changes: 8 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,12 @@ extern crate rspec;

mod color;
pub mod control;
mod error;
mod style;

pub use color::*;

use std::{borrow::Cow, fmt, ops::Deref};
use std::{borrow::Cow, error::Error, fmt, ops::Deref};

pub use style::{Style, Styles};

Expand Down Expand Up @@ -595,6 +596,12 @@ impl fmt::Display for ColoredString {
}
}

impl From<ColoredString> for Box<dyn Error> {
fn from(cs: ColoredString) -> Box<dyn Error> {
Box::from(error::ColoredStringError(cs))
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down