Created
October 8, 2021 16:33
-
-
Save lazywalker/67ccafc37a5f1be3b9e06922152c52aa to your computer and use it in GitHub Desktop.
Extends the `?` operator to Option types by Wrap the Option to Error
This file contains 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
pub trait Sealed {} | |
impl<T> Sealed for Option<T> {} | |
pub trait Context<T, E>: Sealed { | |
/// Wrap the Option to a general error. | |
fn ok(self) -> Result<T, Error>; | |
/// Wrap the Option with additional message | |
fn err<C>(self, context: C) -> Result<T, Error> | |
where | |
C: Display + Send + Sync + 'static; | |
/// Wrap the Option::None with additional message that is evaluated lazily | |
/// only once with Option::unwrap(). | |
fn with_err<C, F>(self, f: F) -> Result<T, Error> | |
where | |
C: Display + Send + Sync + 'static, | |
F: FnOnce() -> C; | |
} | |
impl<T> Context<T, Infallible> for Option<T> { | |
fn ok(self) -> Result<T, Error> { | |
self.ok_or(MessageCode::GENERAL_ERROR.into()) | |
} | |
fn err<C>(self, context: C) -> Result<T, Error> | |
where | |
C: Display + Send + Sync + 'static, | |
{ | |
self.ok_or(Error::msg(context)) | |
} | |
fn with_err<C, F>(self, context: F) -> Result<T, Error> | |
where | |
C: Display + Send + Sync + 'static, | |
F: FnOnce() -> C, | |
{ | |
self.ok_or_else(|| Error::msg(context())) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment