Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- mod msg {
- pub const ERR_ARG_NOT_CONVERTIBLE_TO_UTF_8: &str =
- "Error: Supplied command-line argument not convertible to UTF-8";
- }
- /// THEN: The verbose way
- mod error_verbose {
- use crate::msg;
- use std::{
- ffi::OsString,
- fmt::{Display, Formatter, Result as FmtResult},
- };
- #[derive(Debug, PartialEq)]
- pub enum Error {
- ArgNotConvertibleToUtf8(OsString),
- }
- impl Display for Error {
- fn fmt(&self, f: &mut Formatter) -> FmtResult {
- write!(
- f,
- "{}",
- match self {
- Error::ArgNotConvertibleToUtf8(os_string) => {
- format!("{}: {:?}", msg::ERR_ARG_NOT_CONVERTIBLE_TO_UTF_8, os_string)
- }
- }
- )
- }
- }
- impl From<OsString> for Error {
- fn from(err: OsString) -> Self {
- Error::ArgNotConvertibleToUtf8(err)
- }
- }
- }
- /// NOW: The succinct way
- mod error {
- use crate::msg;
- use derive_more::*;
- #[derive(Debug, Display, From, PartialEq)]
- pub enum Error {
- #[display(fmt = "{}: {:?}", "msg::ERR_ARG_NOT_CONVERTIBLE_TO_UTF_8", "_0")]
- // Optional; use literal or `const` args; `_0` means `self.0`
- ArgNotConvertibleToUtf8(std::ffi::OsString, Context),
- }
- impl std::error::Error for Error {}
- pub enum Context {
- Transfer(/* Sender, Recipient, Amount, Date, etc. etc. etc. */),
- Mint,
- Smelt,
- SomeOtherContext,
- }
- }
- use std::result::Result as StdResult;
- /// Take your pick: `Error` definitions are identical
- type Result<T> = StdResult<T, error::Error>;
- //type Result<T> = StdResult<T, error_verbose::Error>;
- fn main() -> Result<()> {
- /// Will yield `Error::ArgNotConvertibleToUtf8(OsString)`
- /// whenever `OsString` cannot be converted to valid UTF-8 (as per below)
- let _some_arg = std::ffi::OsString::from_vec(vec![b'\xc3', b'\x28'])
- .into_string()
- .map_err(|e| (e, Context::Transfer()))?;
- /* ... do some processing ... */
- Ok(())
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement