Created
February 25, 2026 21:34
-
-
Save malcolmgreaves/ab06526b9484ab2396566ab91230bcae to your computer and use it in GitHub Desktop.
Example of code reduction with thiserror
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
| // These are equivalent: manual `ServerError` impls vs. `thiserror`'s derive macros. | |
| #[derive(Debug)] | |
| enum ServerError { | |
| Io(std::io::Error), | |
| Oxen(OxenError), | |
| } | |
| impl std::error::Error for ServerError {} | |
| impl From<std::io::Error> for ServerError { | |
| fn from(err: std::io::Error) -> Self { | |
| ServerError::Io(err) | |
| } | |
| } | |
| impl From<OxenError> for ServerError { | |
| fn from(err: OxenError) -> Self { | |
| ServerError::Oxen(err) | |
| } | |
| } | |
| impl std::fmt::Display for ServerError { | |
| fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { | |
| match self { | |
| Self::Io(err) => write!(f, "{}", err), | |
| Self::Oxen(err) => write!(f, "{}", err), | |
| } | |
| } | |
| } | |
| //////////////////////////////////////////////////////////////////////////////////////////// | |
| //////////////////////////////////////////////////////////////////////////////////////////// | |
| //////////////////////////////////////////////////////////////////////////////////////////// | |
| #[derive(Debug, Error)] | |
| enum ServerError { | |
| #[error("{0}")] | |
| Io(#[from] std::io::Error), | |
| #[error("{0}")] | |
| Oxen(#[from] OxenError), | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment