Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code shared from the Rust Playground
#![feature(try_trait)]
enum InnerError {
NoneError,
}
trait CustomError: std::error::Error {
fn description(&self) -> &str;
fn cause(&self) -> Option<&std::error::Error> {
None
}
}
impl std::fmt::Display for InnerError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let msg = match &self {
InnerError::NoneError => "NoneError",
};
write!(f, "{}", msg)
}
}
impl std::fmt::Debug for InnerError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", format!("{}", self))
}
}
impl std::error::Error for InnerError {
fn description(&self) -> &str {
match &self {
InnerError::NoneError => "std::error::Error NoneError",
}
}
}
impl CustomError for InnerError {
fn description(&self) -> &str {
match &self {
InnerError::NoneError => "CustomError NoneError",
}
}
}
fn res() -> Result<i32, Box<dyn CustomError>> {
let a = None;
let b = a?;
Ok(b)
}
impl From<std::option::NoneError> for Box<dyn CustomError> {
fn from(_: std::option::NoneError) -> Self {
Box::new(InnerError::NoneError)
}
}
fn main() {
match res() {
Ok(v) => println!("Recieve {}", v),
Err(e) => eprintln!("Error {:?}", e),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment