Created
September 1, 2021 16:33
-
-
Save MInner/8c5db0a4a5cd68bc6cabe0b0bf80df9a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::error::Error; | |
enum TaskError<'a, C> { | |
CustomError(C), | |
StdError(Box<dyn Error + 'a>) | |
} | |
type TaskResult<'a, R, E> = std::result::Result<R, TaskError<'a, E>>; | |
impl<'a, E: Error + 'a, C> From<E> for TaskError<'a, C> { | |
fn from(err: E) -> TaskError<'a, C> { | |
TaskError::StdError(Box::new(err)) | |
} | |
} | |
// --- user code below | |
#[derive(Debug)] | |
enum OurError { | |
NegativeNumber(i32), | |
} | |
type OurResult<'a, R> = TaskResult<'a, R, OurError>; | |
// --- simple quality of life addition | |
impl<'a> From<OurError> for TaskError<'a, OurError> { | |
fn from(custom: OurError) -> TaskError<'a, OurError> { | |
TaskError::CustomError(custom) | |
} | |
} | |
fn ensure_positive<'a>(i: i32) -> OurResult<'a, ()> { | |
if i < 0 { | |
Err(OurError::NegativeNumber(i))? | |
} else { | |
Ok(()) | |
} | |
} | |
fn parse_positive(s: &str) -> OurResult<()> { | |
let a = s.parse::<i32>()?; | |
ensure_positive(a)?; | |
println!("{:}", a); | |
Ok(()) | |
} | |
fn main() { | |
use TaskError::{CustomError, StdError}; | |
for s in vec!["10", "nan", "-10"] { | |
match parse_positive(s) { | |
Ok(()) => {println!("ok!");}, | |
Err(CustomError(e)) => {println!("custom err: {:?}", e);}, | |
Err(StdError(e)) => {println!("std err: {:}", e);}, | |
} | |
} | |
} | |
// Result: | |
// 10 | |
// ok! | |
// std err: invalid digit found in string | |
// custom err: NegativeNumber(-10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment